MySQL: Invalid use of group function MySQL: Invalid use of group function mysql mysql

MySQL: Invalid use of group function


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 pidsFROM Catalog AS c2             -- from catalogWHERE c2.pid = c1.pidHAVING COUNT(c2.sid) >= 2)


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.sidGROUP 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 sids. To make sure you get back only one row per pid I've applied a grouping clause.