2017-10-21 113 views
1

我有一個有許多重複記錄的人的表(名和姓相同)。我試圖編寫一個查詢來列出這些記錄的所有實例。我不想將它們分組,因爲我需要使用成員ID號查看重複記錄。舉例來說,如果我有3個喬·史密斯在餐桌上,我想看看在運行查詢後,此房源:列出重複記錄的所有實例的MySQL查詢

MemberID FirstName LastName 
8746  Joe   Smith 
8944  Joe   Smith 
9774  Joe   Smith 

我嘗試去編寫一個查詢,但它只是列出表中的所有記錄。以下是我試過,沒有做我想做的:

SELECT membership.Member_ID,membership.FirstName,membership.LastName  
FROM membership WHERE membership.FirstName = membership.FirstName AND 
membership.LastName = membership.LastName; 
+0

如果以下任何答案都有解決/幫助你解決你的問題,請接受答案和/或提出答案。謝謝。 –

回答

0

,你可以在這裏自己加入如下:

SELECT distinct 
m1.Member_ID,m1.FirstName,m1.LastName  
FROM membership m1 
inner join membership m2 
on m1.memberid = m2.memberid 
where m1.FirstName = m2.FirstName 
AND m1.LastName = m2.LastName 
and m1.id <> m2.id; 

希望它能幫助!

0

在我看來,分組實際上是走的路。 有一個非常有用的group_concat功能針對這些情況正是:

SELECT FirstName, LastName, GROUP_CONCAT(MemberID) AS ids 
FROM  membership 
GROUP BY FirstName, LastName 
HAVING COUNT(*) > 1 
0

嘗試是這樣的:

SELECT Member_ID, FirstName, LastName  
FROM membership 
WHERE CONCAT(FirstName, LastName) IN (SELECT CONCAT(FirstName, LastName) 
             FROM membership 
             GROUP BY FirstName, LastName 
             HAVING COUNT(*) > 1) 
0

爲了讓你可以使用相關子查詢還

select a.* 
from demo a 
where (
    select count(*) 
    from demo b 
    where a.FirstName = b.FirstName 
    and a.LastName = b.LastName 
) > 1 
所有重複記錄

DEMO