是否可以使用MYSQL GROUP BY选择一堆值

时间:2011-07-01 08:34:16

标签: mysql group-by having

我得到了这样的查询:

SELECT email
FROM abc_table
GROUP BY email
HAVING ( COUNT(email) > 1 )

所以它会归还我:

email   
a@b.com     
c@d.com     
e@f.com

现在我需要调整查询以获得类似的结果:

email       id
a@b.com     1
a@b.com     2   
c@d.com     3
c@d.com     4
c@d.com     5
e@f.com     6

使用GROUP BY HAVING获得此结果是否可行?或者有任何建议来获得这个结果?

非常感谢!

2 个答案:

答案 0 :(得分:2)

SELECT a.email
     , a.id
FROM abc_table a
  JOIN
    ( SELECT email
      FROM abc_table
      GROUP BY email
      HAVING COUNT(email) > 1 
    ) AS ag
    ON ag.email = a.email

答案 1 :(得分:0)

使用GROUP_CONCAT:

SELECT email, GROUP_CONCAT(id) FROM abc_table GROUP BY email

(编辑:误读了这个问题)