2016-08-18 110 views
1

我需要在我的MySQL數據庫表中找到具有相同名稱但具有不同運動項的重複值。 下面是數據的一個例子:如何使用MySQL數據庫中的查詢查找重複項

John Smith Athletics 
Edward Green Athletics 
Edward Green Fencing 
Jim Brown  Rugby 
Jim Brown  Rowing 
Jim Brown  Sailing 
Stan Smith Football 
Stan Smith Football 

嗯,我想打一個查詢這給了我這樣的結果:

Edward Green Athletics 
Edward Green Fencing 
Jim Brown  Rugby 
Jim Brown  Rowing 
Jim Brown  Sailing 

正如我所說的,只是名稱相同的值,但不同的運動,以找到名字。

回答

2

下面是使用exists一個選項:

select * 
from yourtable t 
where exists (
    select 1 
    from yourtable t2 
    where t.name = t2.name and t.sport != t2.sport 
    ) 
0

內選擇獲取所有name小號有一個以上的不同sport。也得到了體育對於這些名字,你必須加入對同桌

select t1.* 
from your_table t1 
join 
(
    select name 
    from your_table 
    group by name 
    having count(distinct sport) > 1 
) t2 on t1.name = t2.name 
+1

你可以添加一些說明? –

-1

沒有suquery另一個posbility將使用與COUNT有:

SELECT * 
FROM yourtable t 
GROUP BY name 
HAVING (COUNT(name) > 1)