简体   繁体   中英

Show all rows in MySQL that contain the same value

I have a MySQL database:

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

How would I return a list of all the columns where the same name appears more than once, eg, I'd like to return this:

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

I've written a count query:

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

But that just returns something like this:

Bob   | 2
James | 2

Whereas I want to return the full rows returned.

Any help would be greatly appreciated, thanks.

You can do it with a sub select

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

Also if your distinction match is multiple columns, you can use cartesian sets:

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

Try this sql query:

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

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM