打印所有重复的行

时间:2011-10-19 21:50:51

标签: mysql sql

现在,我有以下查询,它为我提供了具有相同名称的行的COUNT()。但是,让我们说我只想打印出所有行。

SELECT l.id, c.first_name, c.last_name, 
    l.source AS 'affiliateId', COUNT(*), 
    c.email, ls.create_date, ls.buyer 
  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'
  GROUP BY c.first_name, c.last_name HAVING COUNT(*)>1;

所以我试图从:

joe   smith   3
lisa  martin  2

以下内容:

joe smith   
joe smith
joe smith
lisa martin
lisa martin

帮助!

5 个答案:

答案 0 :(得分:3)

您可以加入数字表:

SELECT T1.col1, T2.col2
FROM
(
   -- your long query goes here
) T1
JOIN numbers
ON numbers.x <= T1.cnt

数字表只是一个包含数字的表:

+---+
| x |
+---+
| 1 |
| 2 |
| 3 |
etc... as many numbers as you will ever need

答案 1 :(得分:2)

你可以使用表达式COUNT(DISTINCT first_name),然后摆脱GROUP BY

所以查询将是

SELECT l.id, c.first_name, c.last_name, l.source AS 'affiliateId', COUNT(DISTINCT c.first_name, c.last_name) as CountRows, 
c.email, ls.create_date, ls.buyer 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'
HAVING CountRows>1

答案 2 :(得分:1)

我不记得MySQL是否支持子查询,但我会做类似

的事情
select
    first, last 
from
    table where id in (select id from table group by first, last having count(*) > 1)
order by
    first, last

答案 3 :(得分:1)

在出现重复的表格上添加另一个联接。对于加入条件,请使标识信息相同(例如c.first_name = c2.first_name AND c.last_name = c2.last_namel.id = c2.id)以及区别不同的记录(例如l.create_date < l2.create_date)。最后,按包含重复项的记录的ID进行分组,或选择不同的行,这样就不会重复。在不知道表模式或重复可能发生的位置的情况下,我不能再具体了。

答案 4 :(得分:0)

将结果集连接到名字和姓氏字段上的联系人故事(假设名字+姓氏形成唯一键)