我正在使用MySQL。以下是我的方案:
供应商(sid:整数,sname:字符串,地址字符串)
部件(pid:整数,pname: string,颜色: string)
目录(sid: integer,pid: integer,cost: real)
(主键以粗体显示)
我正在尝试编写一个查询,以选择至少由两个供应商制造的所有零件:
-- 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 -无效使用组函数
我做错了什么?
发布于 2010-02-25 08:59:06
您需要使用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)
发布于 2010-02-25 08:56:48
首先,您得到的错误是由于使用COUNT
函数的位置造成的--您不能在WHERE
子句中使用聚合(或组)函数。
其次,不使用子查询,而是简单地将表连接到自身:
SELECT a.pid
FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
WHERE a.sid != b.sid
GROUP BY a.pid
我认为它应该只返回这样的行,其中至少有两行具有相同的pid
,但至少有两个sid
。为了确保每个pid
只返回一行,我应用了一个grouping子句。
发布于 2022-02-09 23:28:00
如果where子句中没有聚合函数,则1111 - Invalid use of group function
错误的另一个可能来源是如果您有嵌套的聚合函数:
select sum(avg(close)) from prices;
(1111, 'Invalid use of group function')
您可以通过将问题分解为两个步骤来解决此问题:
中
select @avg:=avg(close) from prices;
运行外部聚合
select sum(@avg) from prices;
https://stackoverflow.com/questions/2330840
复制相似问题