SQL:将条件置于聚合函数的结果上

时间:2010-12-09 10:40:24

标签: php mysql

这件事情很好:

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

但是,当我想把条件放在新列上时,它表示列未找到

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

3 个答案:

答案 0 :(得分:8)

您应该在HAVING子句中将条件放在nr上,如下所示:

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

这是因为nr是聚合函数(COUNT(*))的结果,因此在应用WHERE过滤器时不可用。

编辑:在某些数据库服务器中,对nr的引用不起作用;您也可以使用HAVING COUNT(*) > 100

答案 1 :(得分: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
             GROUP BY c.name
HAVING COUNT(*) > 100
limit 100

答案 2 :(得分:0)

SELECT c.id,c.name,c.ascii_name,COUNT(*)AS nr     来自城市c     INNER JOIN作业j ON(j.city_id = c.id)     WHERE j.is_active = 1和nr.c.id> 100     GROUP BY c.name 限制100