Mysql: Perform of NOT EXISTS. Is it possible to improve permofance?

空扰寡人 提交于 2019-11-27 08:16:15

问题


I have two tables posts and comments. Table comments have post_id attribute. I need to get all posts with type "open", for which there are no comments with type "good" and created date MAY 1.

Is it optimal to use such SQL-query:

SELECT  posts.* FROM  posts  
WHERE NOT EXISTS (
SELECT comments.id FROM comments WHERE comments.post_id = posts.id 
AND  comments.comment_type = 'good' AND 
comments.created_at BETWEEN '2010-05-01 00:00:00' AND '2010-05-01 23:59:59')

I'm not sure that NOT EXISTS is perfect construction in this situation.


回答1:


You are right - you can do better. See this article by Quassnoi for the details but the conclusion is:

That’s why the best way to search for missing values in MySQL is using a LEFT JOIN / IS NULL or NOT IN rather than NOT EXISTS.

Your query rewritten using NOT IN could look like this:

SELECT *
FROM posts  
WHERE posts.id NOT IN (SELECT post_id
                       FROM comments
                       WHERE comments.comment_type = 'good'
                       AND comments.created_at BETWEEN '2010-05-01 00:00:00'
                                                   AND '2010-05-01 23:59:59')



回答2:


No idea whether it is faster, you could check it out:

SELECT * FROM posts
LEFT JOIN comments 
ON comment.postid = post.id
AND comment.comment_type='good'
WHERE comment.postid IS NULL

Assuming postid is never NULL / a non NULLable column.



来源:https://stackoverflow.com/questions/2993332/mysql-perform-of-not-exists-is-it-possible-to-improve-permofance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!