我构建了这个查询以向我展示分支机构中有多少员工和客户,它给了我重复项,因此我需要对它们进行分组。但是,当我添加组时,查询无效。任何人都知道为什么?
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;
答案 0 :(得分:2)
这个查询最好写成:
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
语法。切勿在{{1}}子句中使用逗号。FROM
。GROUP BY
被声明为branchId
上的主要密钥或唯一密钥,则原始查询符合ANSI标准。但是,大多数数据库仍然不接受查询。答案 1 :(得分:0)
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, B.branchName;
大多数数据库需要按项目列表==在聚合函数之前选择项目列表
答案 2 :(得分:0)
SELECT B.branchID,B.branchName,COUNT(E.staffNo)AS" No。员工",COUNT(C.customerID)AS" No。客户" FROM Branch B在E.employeeBranchID = B.branchID上离开加入Employee E在B.branchID = C.customerBranchID上加入Customer C GROUP BY B.branchID;