帮助优化这个mysql查询

时间:2011-02-20 11:40:41

标签: mysql query-optimization

好朋友,我有这个查询有效,但执行时间很长。我想知道是否有更快的方法来实现这一点。

SELECT id, email FROM member WHERE email IN 
(SELECT email FROM member GROUP BY email HAVING count( * ) >1 ) 
ORDER BY `email` ASC

基本上,有些条目中同一封电子邮件不止一次出现,我只是希望在“电子邮件”重复的条目中返回这些行。

上述查询在这个方向上有效,但是很长。

干杯。

5 个答案:

答案 0 :(得分:2)

您可以先将结果分组,然后将它们连接到成员表,以确保只显示包含重复电子邮件的行。

SELECT m.id, m.email
FROM member m JOIN (
    SELECT email 
    FROM member 
    GROUP BY email 
    HAVING COUNT(*) > 1
  ) g ON m.email = g.email
ORDER BY m.email ASC

答案 1 :(得分:1)

由于嵌套选择,您的查询很慢,每次都会重新计算。最好的解决方案是重写您的算法,以便您可以使用如下查询:

SELECT id, email 
FROM member GROUP BY email
HAVING count( * ) >1
ORDER BY `email`

不幸的是,你回来的id将是每个组中的随机选择。这可能是一个更有用的查询:

SELECT GROUP_CONCAT(id), email 
FROM member GROUP BY email
HAVING count( * ) >1
ORDER BY `email`

答案 2 :(得分:0)

你能分两个阶段做到吗?首先创建一个包含>所有电子邮件的临时表1出现,然后通过电子邮件字段将主表连接到临时表...

如果您的成员表在电子邮件字段中有索引,那么这应该非常快。


CREATE TEMPORARY TABLE ddd
SELECT email, count(*) as cnt FROM member GROUP BY email HAVING cnt>1;

SELECT * FROM ddd
INNER JOIN member USING (email);

答案 3 :(得分:-1)

当您只需要做一次

时,您正在进行两次查询
SELECT id, email 
FROM member
GROUP BY email 
HAVING count( * ) > 1
ORDER BY `email` ASC

答案 4 :(得分:-1)

select id,email,count(*) as n from member group by id having n > 1;