我有一个名为lnk_lists_addresses
的遗留MySQL表,列list_id
和address_id
。我想编写一个查询报告所有相同的list_id
- address_id
组合在表格中出现多次的情况。
我试过了......
SELECT count(*), list_id, address_id
FROM lnk_lists_addresses
GROUP BY list_id, address_id
ORDER BY count(*) DESC
LIMIT 20
它有效,因为重复次数少于20次。但是,我如何只返回大于1的计数?
我尝试在WHERE count(*) > 1
之前和之后添加“GROUP BY
”,但是错误地说该声明无效。
答案 0 :(得分:8)
SELECT count(*), list_id, address_id
FROM lnk_lists_addresses
GROUP BY list_id, address_id
HAVING count(*)>1
ORDER BY count(*) DESC
将我和Todd.Run的答案结合起来,以获得更“完整”的答案。您想使用HAVING子句:
答案 1 :(得分:2)
您想使用“HAVING”子句。它的用法在MySQL手册中有解释。
答案 2 :(得分:1)
SELECT count(*) AS total, list_id, address_id
FROM lnk_lists_addresses
WHERE total > 1
GROUP BY list_id, address_id
ORDER BY total DESC
LIMIT 20
如果您为COUNT()字段命名,则可以稍后在语句中使用它。
编辑:忘了HAVING
(> _<)