2015-12-30 64 views
1

我有一個表是這樣的:如何選擇具有一個不同值和多個重複值的行?

// mytable 
+----+--------------------------+---------------+-----------------+ 
| id |   Email   |  IP  |  cookies  | 
+----+--------------------------+---------------+-----------------+ 
| 1 | [email protected]  | 172.95.65.7 | 5c6ffbdd40d95 | 
| 2 | [email protected]  | 84.15.2.4  | 26b73a21e63c3 | 
| 3 | [email protected]  | 124.54.32.1 | e0e904b73a2fe | 
| 4 | [email protected]  | 172.95.65.7 | 5c6ffbdd40d95 | 
| 5 | [email protected]  | 56.23.41.3 | b23a51a63edf4 | 
| 6 | [email protected]  | 84.15.2.4  | 26b73a21e63c3 | 
+----+--------------------------+---------------+-----------------+ 

現在我要選擇第一和第四行。因爲它們具有相同的IP,相同的Cookies和不同的Email。我怎樣才能選擇它們?

我想這輸出:

// newmytable 
+----+--------------------------+---------------+-----------------+ 
| id |   Email   |  IP  |  cookies  | 
+----+--------------------------+---------------+-----------------+ 
| 1 | [email protected]  | 172.95.65.7 | 5c6ffbdd40d95 | 
| 4 | [email protected]  | 172.95.65.7 | 5c6ffbdd40d95 | 
+----+--------------------------+---------------+-----------------+ 
+0

如何知道相同? –

+0

@GoudaElalfy Whaat?因爲它們是一樣的。 '172.95.65.7'和'172.95.65.7'是相同的。 – stack

回答

1

您可以使用exists作爲

select m1.* from mytable m1 
where exists (
    select 1 from mytable m2 
    where 
    m1.Email <> m2.Email 
    and m1.IP = m2.IP 
    and m1.cookies = m2.cookies 
) 
+0

非常好+1。只有一件事,我可以使用'IN'而不是'EXISTS'嗎? – stack

+1

對於大型數據集'exit「,優化https://dev.mysql.com/doc/refman/5.5/en/subquery-optimization-with-exists.html對於表格中的正確索引,它肯定表現更好。 –

0

試試這個,它會幫助你

SELECT id, Email,IP, cookies, COUNT(*) FROM mytable GROUP BY IP, cookies HAVING COUNT(*) > 1 
+0

我沒有檢查它,但感謝+1,爲你付出的努力。 – stack

0

這裏的解決方案,而無需使用子查詢,基本上是另一種查詢方式。

SELECT m1.* 
FROM mytable m1,mytable m2 
WHERE (m1.`Email`<> m2.`Email`) AND (m1.`IP`=m2.`IP`) AND (m1.`cookies`=m2.`cookies`); 
相關問題