2

I want to display the results such that:

record number is ordered by the number of items attached to it

IF

the number of items attached is greater than 100

SELECT r.number,
       r.title,
       COUNT(i.itemnumber)
FROM record r
LEFT JOIN items i ON (r.number = i.number)
WHERE r.title REGEXP 'SQL for idiots'
AND COUNT(i.itemnumber) > 100
GROUP BY r.number
ORDER BY COUNT(i.itemnumber)

This throws the old:

ERROR 1111 (HY000): Invalid use of group function

I've tried a 'HAVING' clause with no luck either.

Got it!:

Had to swap lines with my ORDER clause:

HAVING COUNT(i.itemnumber) > 100
ORDER BY COUNT(i.itemnumber)
OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Bubnoff
  • 3,917
  • 3
  • 30
  • 33

1 Answers1

4

You test the results of an aggregate function with a HAVING clause.

SELECT r.number,
       r.title,
       COUNT(i.itemnumber)
FROM record r
LEFT JOIN items i ON (r.number = i.number)
WHERE r.title REGEXP 'SQL for idiots'
GROUP BY r.number
HAVING COUNT(i.itemnumber) > 100
ORDER BY COUNT(i.itemnumber)
Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235