查找表中的所有重复行

时间:2011-10-19 16:22:46

标签: mysql sql

假设我有下表

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';

4 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分: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
)

答案 2 :(得分: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 :(得分:0)

如何使用“SELECT DISTINCT ...”? 不是这样做的吗?