Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Putting condition on result of an aggregate function

Tags:

php

mysql

this thing works fine:

SELECT c.id, c.name, c.ascii_name, COUNT(*) AS nr
    FROM cities c 
    INNER JOIN jobs j ON (j.city_id = c.id ) 
    WHERE j.is_active = 1 
    GROUP BY c.name
limit 100

but when i wanna put condition on new column nr it says column not found

SELECT c.id, c.name, c.ascii_name, COUNT(*) AS nr
    FROM cities c 
    INNER JOIN jobs j ON (j.city_id = c.id ) 
    WHERE j.is_active = 1 and nr > 100
    GROUP BY c.name
limit 100
like image 817
ehmad11 Avatar asked Dec 09 '10 10:12

ehmad11


1 Answers

You should put the condition on nr in the HAVING clause, like this:

SELECT c.id, c.name, c.ascii_name, COUNT(*) AS nr
    FROM cities c 
    INNER JOIN jobs j ON (j.city_id = c.id ) 
    WHERE j.is_active = 1
    GROUP BY c.name
    HAVING nr > 100
limit 100

This is because nr is the result of an aggregate function (COUNT(*)) and as such is not available at the time the WHERE filter is applied.

EDIT: in some database servers, the reference to nr doesn't work; you can also use HAVING COUNT(*) > 100.

like image 84
Spiny Norman Avatar answered Sep 27 '22 21:09

Spiny Norman