我正在尝试计算每amount
个fk_id
的变体数量。如果有多个变体,那么我希望返回记录,否则我希望忽略记录。
以下陈述有什么问题?
SELECT *, count(fk_id) AS `count` FROM table
WHERE count > 1
GROUP BY fk_id, amount;
表:
+-----------+----------+--------------+
| id | fk_id | amount |
+-----------+----------+--------------+
| 1 | 100 | 5 |
| 2 | 200 | 10 |
| 3 | 200 | 10 |
| 4 | 200 | 10 |
| 5 | 200 | 15 |
+-----------+----------+--------------+
预期产出:
+-----------+----------+--------------+--------------+
| id | fk_id | amount | count |
+-----------+----------+--------------+--------------+
| 2 | 200 | 10 | 2 |
+-----------+----------+--------------+--------------+
答案 0 :(得分:2)
您不能在WHERE
子句中使用聚合函数。请改用HAVING
子句:
SELECT MIN(id) as id,fk_id,amount, count(fk_id)-1 AS `count`
FROM table
GROUP BY fk_id, amount
HAVING count(fk_id)>1
结果:
ID FK_ID AMOUNT COUNT
2 200 10 2
请参阅SQL Fiddle中的结果。