子查询不在性能问题中

发布于 2024-09-28 20:58:36 字数 545 浏览 4 评论 0原文

我有一个缓慢的查询,

select * from table1 where id NOT IN ( select id from table2 )

通过执行以下操作会更快(不确定这是否可能):

select * from table1 where id not in ( select id from table2 where id = table1.id )

或者:

select * from table1 where table1.id NOT EXIST( select id from table2 where table2.id = table1.id )

或者:

select * from table1
left join table2 on table2.id = table1.id
WHERE table2.id is null

或者做其他事情?就像把它分成两个查询一样......

I have this slow query

select * from table1 where id NOT IN ( select id from table2 )

Would this be faster by doing something like (not sure if this is possible):

select * from table1 where id not in ( select id from table2 where id = table1.id )

Or:

select * from table1 where table1.id NOT EXIST( select id from table2 where table2.id = table1.id )

Or:

select * from table1
left join table2 on table2.id = table1.id
WHERE table2.id is null

Or do something else? Like break it up into two queries ...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅听莫相离 2024-10-05 20:58:36

问题是 - 比较中的字段是否可以为空(即列值可以为 NULL)吗?

如果它们可以为空...

...在 MySQL 中 NOT INNOT EXISTS 性能更好 - 请参阅 此链接

如果它们NOT可为空...

... LEFT JOIN / IS NULL 表现更好 - 请参阅此链接

The question is - are the field(s) in the comparison nullable (meaning, can the column value be NULL)?

If they're nullable...

...in MySQL the NOT IN or NOT EXISTS perform better - see this link.

If they are NOT nullable...

... LEFT JOIN / IS NULL performs better - see this link.

怀中猫帐中妖 2024-10-05 20:58:36
select table1.* from table1 
LEFT JOIN table2 ON table1.id = table2.id
WHERE table2.id IS NULL

目的是摆脱 NOT IN

select table1.* from table1 
LEFT JOIN table2 ON table1.id = table2.id
WHERE table2.id IS NULL

The object being to get rid of NOT IN

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文