首页 > 解决方案 > 不在 LIKE 中的 SQL

问题描述

我在一个表中有一个电子邮件地址列表,在另一个表中有一个域列表。仅当他们的电子邮件没有在域表中设置域时,我才想从电子邮件表中查询电子邮件。

email                               domains
------                              -------

a@google.com                       yahoo.com
a@yahoo.com                        ebay.com
a@ebay.com
a@gmail.com

所以只有 a@google.com 和 a@gmail.com 应该是查询的结果。

我遇到的问题是我在 emails 表中有大约 600 万行,即使使用适当的索引也需要很长时间才能查询。有没有更好的方法来解决这个问题?我也觉得使用 concat 没有帮助,因为当您使用函数时,它不再使用索引?

这是我的查询:

SELECT
 email
FROM
    emails
    LEFT JOIN `domains` ON emails.email LIKE CONCAT( '%', domains.domain, '%' ) 
WHERE
    AND `domains`.`domain` IS NULL

标签: mysqlsql

解决方案


我会使用这样的子查询:

select e.*
from email e
where not exists (select 1
                  from domains d
                  where e.email like concat('%', d.domain)
                 );

但是,您可能可以使用此版本获得更好的性能:

select e.*
from email e
where not exists (select 1
                  from domains d
                  where substring_index(e.email, '@', -1) = d.domain
                 );

等式可能使在 上使用索引成为可能domains(domain)


推荐阅读