我正在尝试发现表中所有行多次出现的外键,并通过子查询返回这些外键。
在列上使用GROUP BY
我能够可视化每个外键的COUNT
:
SELECT orders_id, COUNT(*) as count
FROM order_history
GROUP BY orders_id
但是当我用WHERE子句扩充它以尝试过滤时,像这样:
SELECT orders_id, COUNT(*) as count
FROM order_history
GROUP BY orders_id
WHERE count > 1
我收到错误
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE count > 1 LIMIT 0, 30' at line 4
显然count
没有资格进行比较,WHERE
会被评估吗?
:发布回复更新:
感谢您的快速回复! HAVING
正是我所缺少的。我发现这个问题有助于扩展主题:WHERE vs HAVING
答案 0 :(得分:3)
要将过滤应用于COUNT(),SUM(),MAX(),MIN()
等聚合值,请使用HAVING
子句而不是WHERE
。
SELECT orders_id, COUNT(*) as count
FROM order_history
GROUP BY orders_id
HAVING count > 1
语法错误是由于WHERE
子句必须位于GROUP BY
子句之前。但是,即使它位于正确的位置,它仍然会出错,因为在count
子句计算时WHERE
别名是未知的。
来自MySQL SELECT
syntax documentation:
HAVING子句可以引用SELECT列表或外部子查询中的select_expr中指定的任何列或别名,以及聚合函数。
答案 1 :(得分:1)
您不能将where clause
与group by clause
一起使用,在这种情况下,您必须使用having
SELECT orders_id, COUNT(*) as count
FROM order_history
GROUP BY orders_id
having count > 1