我建立了此查询以显示分支机构有多少员工和客户,它给了我重复项,因此我需要对它们进行分组。但是,当我添加分组依据时查询无效。有人知道为什么吗?
SELECT B.branchID, B.branchName, COUNT(E.staffNo) AS "No. Of Employees", COUNT(C.customerID) AS "No. Of Customers"
FROM Branch B, Employee E, Customer C
WHERE E.employeeBranchID = B.branchID
AND B.branchID = C.customerBranchID
GROUP BY B.branchID;
最佳答案
此查询最好写成:
SELECT B.branchID, B.branchName, COUNT(E.staffNo) AS "No. Of Employees", COUNT(C.customerID) AS "No. Of Customers"
FROM Branch B JOIN
Employee E
ON E.employeeBranchID = B.branchID JOIN
Customer C
ON B.branchID = C.customerBranchID
GROUP BY B.branchID, B.branchName;
如果您处于ANSI模式,则MySQL的行为类似于大多数其他数据库,并且由于未汇总
B.branchName
,因此将返回错误。笔记:
使用显式
JOIN
语法。切勿在FROM
子句中使用逗号。所有未聚合的列都在
GROUP BY
中。如果将
branchId
声明为branch
上的主键或唯一键,则原始查询符合ANSI。但是,大多数数据库仍不接受该查询。关于mysql - 使用分组依据时,SQL查询无法运行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35796223/