mysql - 不在 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
解决方案
我会使用这样的子查询:
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)
。
推荐阅读
- javascript - 在 Acrobat 中旋转页面的脚本
- python - 你能用visual basic运行一个python文件吗
- r - 转换时间戳而不添加 yyyy-mm-dd
- java - 无法停止前台服务 stopSelf() 和 stopForeground(true) 不工作
- php - move_uploaded_file 只在 IE 中保存空文件
- javascript - Jquery 点击函数(取决于点击哪个 MYSQL Result div 实例)?
- haskell - 当我的 getter 和 setter 返回“Either”时,我可以构建类似镜头的东西吗?
- javascript - 在 Electron WebView 中转换内容的最佳实践是什么?
- javascript - React-未处理的拒绝(TypeError):无法读取未定义的属性“城市”
- android - androidx.RecyclerView ListAdapter 很慢