MySQL,按特定外键的出现次数进行过滤

时间:2012-12-28 20:56:57

标签: mysql

我正在尝试发现表中所有行多次出现的外键,并通过子查询返回这些外键。

在列上使用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

2 个答案:

答案 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 clausegroup by clause一起使用,在这种情况下,您必须使用having

SELECT orders_id, COUNT(*) as count
FROM order_history
GROUP BY orders_id
having count > 1