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

后端 未结 2 1619
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-11 18:36

I have two tables posts and comments. Table comments have post_id attribute. I need to get all p

相关标签:
2条回答
  • 2020-12-11 19:17

    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.

    0 讨论(0)
  • 2020-12-11 19:37

    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')
    
    0 讨论(0)
提交回复
热议问题