2011-10-19 124 views
3

比方說,我有如下表查找所有重複表中的行

first last  value 
tony jones  1 
james guy  5 
sara miller 6 
tony jones  2 
sara miller 3 
joe  cool  4 
david marting 7 

是否有一個命令來快速查詢所有重複行。

所以我最終會:

first last  value 
tony jones  1 
tony jones  2 
sara miller 6 
sara miller 3 

幫助!

這是我需要這個添加到查詢:

SELECT l.create_date, l.id, c.first_name, c.last_name, c.state, c.zipcode, 
l.source AS 'affiliateId', ls.buyer, ls.amount FROM lead_status AS ls 
INNER JOIN leads AS l ON l.id = ls.lead_id 
INNER JOIN contacts AS c ON c.lead_id = l.id 
WHERE ls.discriminator = 'AUTO_POST' AND l.affiliate_id=1003 
AND ls.winner =1 AND l.test =0 AND l.create_date BETWEEN '2011-10-03' AND '2011-10-19'; 
+0

每個第一個/最後一個組合的值是唯一的嗎? –

+0

是的,他們只是名字和姓氏。 – ATMathew

+0

你只想選擇或刪除重複? – user973254

回答

4
SELECT t1.* 
FROM <table> t1, <table> t2 
WHERE t1.first=t2.first AND 
    t1.last=t2.last AND 
    t1.value<>t2.value 
; 
+0

+1雖然我會將隱式連接更改爲明確的「INNER JOIN」 –

+1

您需要說'SELECT DISTINCT ...'或更改您的查詢。如果我們有行('tony','jones',1),('tony','jones',2)和('tony','jones',3),會發生什麼?你會得到三個以上的'託尼瓊斯'記錄...... – pilcrow

2

如果你只是想重複....

select t2.first, t2.last , t1.value from (
     select first, last, count(*) from your_table 
     group by first, last 
     having count(*)>1 
    ) t2 inner join your_table t1 on (t1.first=t2.first and t1.last=t2.last) 

此外,

select first, last , count(*) from your_table 
group by first, last 

將返回第一,最後一列和記錄重複次數的額外列

3

這應該有效地做到這一點,假設正確的索引,且這個值的每一行是唯一的:

SELECT first, 
     last, 
     value 
FROM MyTable AS T1 
WHERE EXISTS (-- Is there another row with the same first/last name, 
    SELECT *  -- but a different value 
    FROM MyTable AS T2 
    WHERE T2.first=T1.first 
    AND T2.last=T1.last 
    AND T2.value<>T1.value 
) 
0

如何只使用「SELECT DISTINCT ...」? 它不是做這份工作嗎?