在MYSQL Where子句中使用COUNT(*)AS`COUNT`

时间:2014-04-11 22:57:30

标签: mysql count

我正在尝试查找,计算和报告列中所有重复条目的实例。任何想法如何做到这一点类似于我下面的尝试。

SELECT `Id`, COUNT(*) AS `COUNT`
FROM `testproductdata`
WHERE `COUNT` > 1
GROUP BY `Id`
ORDER BY `COUNT` DESC;

我收到1054错误:where子句中的未知列COUNT

4 个答案:

答案 0 :(得分:3)

HAVINGWHERE

一起使用GROUP BY
SELECT `Id`, COUNT(*) AS `COUNT`
FROM `testproductdata`
GROUP BY `Id`
HAVING  `COUNT` > 1
ORDER BY `COUNT` DESC;

我建议将count(*)上的相关名称用作total_count而不是COUNT

更改查询如下:

SELECT `Id`, COUNT(*) AS `total_count`
FROM `testproductdata`
GROUP BY `Id`
HAVING  `total_count` > 1
ORDER BY `total_count` DESC;

答案 1 :(得分:1)

尝试将DISTINCT添加到查询

SELECT * FROM (
SELECT DISTINCT `Id`, (SELECT COUNT(Id) FROM `testproductdata` WHERE `Id`=`Id`) `count`
FROM `testproductdata`
GROUP BY `Id`
HAVING `count` > 1
)
ORDER BY `count` DESC;

答案 2 :(得分:1)

你应该改变拥有的地方,这应该有效:

SELECT Id, COUNT(1) AS count
FROM testproductdata
GROUP BY Id
HAVING COUNT(1) > 1
ORDER BY COUNT(1) DESC;

答案 3 :(得分:0)

试试这个

select * from 
(SELECT `Id`, COUNT(*) AS `c`
FROM `testproductdata`
group by `Id`)
WHERE `c` > 1
ORDER BY `c` DESC;

SELECT `Id`, COUNT(*) AS `c`
FROM `testproductdata`
group by `Id`
having `c` > 1
ORDER BY `c` DESC;