Mysql Select Distinct w TRIM()和Subselect Optimize Performance

时间:2015-01-26 16:53:10

标签: mysql performance subquery distinct trim

我有一个表mailing_list,其中包含

id, optout, email

电子邮件有重复,但即使电子邮件是,也不会选择退出 相同。所以我们可以得到这样的数据......

id optout email

1   0     test1@email.com
2   1     test1@email.com
3   0     test1@email.com
4   0     test2@email.com
5   1     test3@email.com
6   0     test4@email.com
7   1     test4@email.com
8   0     test4@email.com

我试图实现的最终结果是两个列表,optin和optout

到目前为止,我发现这样做的最好方法是使用以下查询, 但性能非常慢,所以试图找到更好的方法。 TRIM 函数需要在那里,因为一些电子邮件有whitspace 有些人在选择不同时不这样做,如果我,我仍会得到欺骗 不要使用TRIM。

OPTIN

select distinct TRIM(email) as emails from mailing_list where optout = 0
and email not in (select email from mailing_list where optout = 1) order by emails

OPTOUT

select distinct TRIM(email) as emails from mailing_list where optout = 1
and email not in (select email from mailing_list where optout = 0) order by emails

非常感谢任何帮助。

由于

1 个答案:

答案 0 :(得分:2)

对于那些选择退出的人:

select trim(email) as trimmed_email, sum(optout) as qty
from mailing_list
group by trimmed_email
having qty > 0;

对于那些选择加入的人:

select trim(email) as trimmed_email, sum(optout) as qty
from mailing_list
group by trimmed_email
having qty = 0;