MySQL: Invalid use of group function
First, the error you're getting is due to where you're using the COUNT
function -- you can't use an aggregate (or group) function in the WHERE
clause.
Second, instead of using a subquery, simply join the table to itself:
SELECT a.pid
FROM Catalog as a LEFT JOIN Catalog as b USING( pid )
WHERE a.sid != b.sid
GROUP BY a.pid
Which I believe should return only rows where at least two rows exist with the same pid
but there is are at least 2 sid
s. To make sure you get back only one row per pid
I've applied a grouping clause.
You need to use HAVING
, not WHERE
.
The difference is: the WHERE
clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT
function.
HAVING
is like WHERE
, only it happens after the COUNT
value has been computed, so it'll work as you expect. Rewrite your subquery as:
( -- 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)