I’m not very good at using complicated MySQL, so I’m stuck with a somewhat complicated (but still pretty basic, I think) situation:
I have 3 tables:
- Table A has 2 records, one with ID 1, one with ID 2. They both have a
foreign key to Table B, which is the same. - Table B currently has only
one record, but will have more in the future. - Table C has multiple
records, all with a reference to either record 1 or 2 in Table A.
What I want to achieve:
I want to select all (or some) information about Table A’s records, but only for those records that reference to the record in Table B. Now here’s the catch for me: I want to order the results, starting with the one which has the most records in Table C referring to it.
So:
SELECT COUNT(C.*) AS NUMBER_OF_RECORDS, A.*
FROM `TableA` A, `TableB` B, `TableC` C
WHERE A.bID = 1 AND C.aID = A.ID
ORDER BY NUMBER_OF_RECORDS DESC;
Something like that, except that this doesn’t work for C.aID = A.ID. I hope the above query will just make my intentions more clear.
Any help greatly appreciated!
Better view of the situation with sample data
Tables:
- Department
- Location
- Employee
So now say, I would want to select all data of the departments in one location, ordered by the amount of employees.
Desired output:
departmentID, departmentName, no_of_emps
1, Sales, 14
2, Finance, 12
3, Management, 6
1 Answer