显示MySQL中包含相同值的所有行

时间:2010-09-26 12:38:37

标签: php mysql

我有一个MySQL数据库:

ID | Name
1  | Bob
2  | James
3  | Jack
4  | Bob
5  | James

如何返回同名出现不止一次的所有列的列表,例如,我想返回此内容:

1  | Bob
2  | James
4  | Bob
5  | James

我写了一个计数查询:

SELECT Name, COUNT(Name) 
AS NumOccurrences 
FROM table 
GROUP BY Name 
HAVING ( COUNT(Name) > 1 )

但这只会返回这样的内容:

Bob   | 2
James | 2

而我想返回返回的完整行。

非常感谢任何帮助,谢谢。

3 个答案:

答案 0 :(得分:21)

您可以使用子选择

来完成
SELECT * FROM table WHERE Name IN (
    SELECT Name FROM table GROUP BY Name HAVING count(*) > 1
)

此外,如果您的区别匹配是多列,则可以使用笛卡尔集:

SELECT * FROM table WHERE (firstName, lastName) IN (
    SELECT firstName, lastName FROM table GROUP BY firstName, lastName HAVING count(*) > 1
)

答案 1 :(得分:8)

试试这个SQL查询:

select distinct a.name, a.id 
from table a, table b 
where a.name = b.name and a.id != b.id

答案 2 :(得分:4)

试试这个

SELECT Name, COUNT(Name) AS NumOccurrences 
FROM table 
GROUP BY Name 
HAVING COUNT(*) > 0