MySQL:无效使用组函数
我正在使用MySQL。这是我的架构:
供应商( ,sname:字符串,地址字符串)
零件( ,pname:字符串,color:字符串)
目录( ,成本:实数)
(主键以粗体显示)
我正在尝试编写查询以选择至少两个供应商制造的所有零件:
-- Find the pids of parts supplied by at least two different suppliers.SELECT c1.pid -- select the pid
FROM Catalog AS c1 -- from the Catalog table
WHERE c1.pid IN ( -- where that pid is in the set:
SELECT c2.pid -- of pids
FROM Catalog AS c2 -- from catalog
WHERE c2.pid = c1.pid AND COUNT(c2.sid) >= 2 -- where there are at least two corresponding sids
);
首先,我什至会以正确的方式这样做吗?
其次,我得到这个错误:
1111-无效使用组功能
我究竟做错了什么?
回答:
您需要使用HAVING
,不WHERE
。
区别在于:该WHERE
子句过滤MySQL选择的行。 然后, MySQL将这些行分组在一起,并为您的COUNT
函数汇总数字。
HAVING
就像是WHERE
,只有它发生 后, 该COUNT
值已经计算出来,所以你希望它会工作。将子查询重写为:
( -- where that pid is in the set:SELECT c2.pid -- of pids
FROM Catalog AS c2 -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)
以上是 MySQL:无效使用组函数 的全部内容, 来源链接: utcz.com/qa/422437.html