mysql SQL:在聚合函数的结果上放置条件

jtw3ybtb  于 12个月前  发布在  Mysql
关注(0)|答案(3)|浏览(125)

这很好用:

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

字符串
但是当我想把条件放在新列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 and nr > 100
    GROUP BY c.name
LIMIT 100

1aaf6o9v

1aaf6o9v1#

你应该把条件放在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是一个聚合函数(*)的结果,因此在应用WHERE过滤器时不可用。
编辑:在某些数据库服务器中,对nr的引用不起作用;您也可以使用HAVING COUNT(*) > 100

iqxoj9l9

iqxoj9l92#

选择c.id,c.name,c. asidom_name,(*)AS nr从城市c内部加入工作j ON(j.city_id = c.id)其中j.is_active = 1和nr.c.id> 100 GROUP BY c.name limit 100

kb5ga3dv

kb5ga3dv3#

你应该把你的声明改为

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

字符串

相关问题