此查询工作正常:
SELECT leads.contact_id, count(leads.contact_id) as orders
FROM leads
WHERE leads.status="sold"
GROUP BY leads.contact_id
但是这个没有。为什么?
SELECT leads.contact_id, count(leads.contact_id) as orders
FROM leads
WHERE orders > 1 and leads.status="sold"
GROUP BY leads.contact_id
执行此查询时出现错误
1054-“ where子句”中的未知列“ orders”
即使用计数(leads.contact_id)替换订单,它也不起作用:
SELECT leads.contact_id, count(leads.contact_id) as orders
FROM leads
WHERE count(leads.contact_id) > 1 and leads.status="sold"
GROUP BY leads.contact_id
返回以下错误消息:
1111-无效使用组功能
答案 0 :(得分:1)
如果您了解SQL的操作顺序,您将知道为什么查询不起作用。
FROM clause
WHERE clause
GROUP BY clause
HAVING clause
SELECT clause
ORDER BY clause
WHERE
子句在SELECT
和GROUP BY
之前进行评估。因此它将不知道count(leads.contact_id)
或orders
是什么。另一方面是HAVING
之后的GROUP BY
。用于过滤聚合。
SELECT leads.contact_id, count(leads.contact_id) as orders
FROM leads
WHERE leads.status="sold"
GROUP BY leads.contact_id
HAVING orders > 1
答案 1 :(得分:0)
我应该使用 HAVING 而不是 WHERE ,因为WHERE仅可用于过滤原始数据表,而不能用于过滤计算出的数据表。但是列 count(leads.contact_id)或 orders 是计算列,而不是表的原始列,因此我必须像这样使用HAVING才能使其工作: / p>
SELECT leads.contact_id, count(leads.contact_id) as orders
FROM leads
WHERE leads.status="sold"
GROUP BY leads.contact_id
HAVING orders>1
也请参见此detailed explanation