5

This 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 want to put the condition on th 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
1
  • please explain what type of error you are getting..? Commented Dec 9, 2010 at 10:43

3 Answers 3

15

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.

0
0

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.c.id > 100 GROUP BY c.name limit 100

0

you should put your statement should read

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 COUNT(*) > 100
limit 100

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.