我不太擅长使用复杂的MySQL,所以我遇到了一个有点复杂(但仍然很基本,我认为)的情况:
我有3张桌子:
我想要实现的目标: 我想选择关于表A记录的所有(或一些)信息,但仅针对那些引用表B中记录的记录。现在这里是我的问题:我想订购结果,从具有表C中的大多数记录都是指它。
所以:
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;
类似的东西,除了这对C.aID = A.ID
不起作用。我希望上面的查询能让我的意图更清晰。
任何帮助都非常感谢!
使用示例数据更好地了解情况
表:
现在说,我想在一个地方选择所有部门的数据,按雇员数量排序。
期望的输出:
departmentID,departmentName,no_of_emps
1,销售,14
2,财务,12
3,管理,6
答案 0 :(得分:1)
SELECT
COUNT(C.aID) AS NUMBER_OF_RECORDS
, A.*
FROM
`TableA` A
JOIN
`TableB` B
ON B.ID = A.bID
LEFT JOIN --- so you also get rows from A (and B)
`TableC` C --- that have no matching rows in C
ON C.aID = A.ID
GROUP BY
A.ID
ORDER BY
NUMBER_OF_RECORDS DESC;
答案 1 :(得分:0)
这可以给你你想要的东西:
SELECT A.departmentId, A.departmentName, COALESCE(no_of_emps,0) no_of_emps
FROM Department A
INNER JOIN Location B
ON A.LocationId = B.LocationId
LEFT JOIN ( SELECT departmentId, COUNT(*) no_of_emps
FROM Employee
GROUP BY departmentId) C
ON A.departmentId = C.departmentId
WHERE A.LocationId = 123
ORDER BY COALESCE(no_of_emps,0) DESC
答案 2 :(得分:0)
这应该有效:
SELECT `D`.`departmentId`, `D`.`departmentName`, COUNT(`E`.`employeeId`) AS `no_of_emps`
FROM `Department` `D`
INNER JOIN `Location` `L` ON `D`.`departmentId` = `L`.`departmentId`
INNER JOIN `Employee` `E` ON `D`.`departmentId` = `E`.`departmentId`
WHERE `L`.`locationId` = 1
ORDER BY `no_of_emps` DESC;
请根据您的架构替换表名和列名。
希望它有所帮助。
答案 3 :(得分:-1)
你想得到A的所有元组按照引用它的C元组的数量排序吗?
SELECT A.* FROM A,
(SELECT COUNT(*) cnt FROM C WHERE C.aid = A.ID) CNT
ORDER BY CNT.cnt