5

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
1
  • please explain what type of error you are getting..? 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

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

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