【问题标题】:Mysql: Perform of NOT EXISTS. Is it possible to improve perfomance?Mysql:如果不存在则执行。是否可以提高性能?
【发布时间】:2011-02-28 22:00:01
【问题描述】:

我有两个表 postscmets。表 cmets 具有 post_id 属性。我需要获取所有类型为“open”的posts,其中没有类型为“good”且创建日期为 5 月 1 日的 cmets

使用这样的 SQL 查询是否最佳:

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')

我不确定 NOT EXISTS 在这种情况下是完美的构造。

【问题讨论】:

    标签: mysql performance not-exists


    【解决方案1】:

    你是对的——你可以做得更好。详情见this articleQuassnoi,但结论是:

    这就是为什么在 MySQL 中搜索缺失值的最佳方法是使用 LEFT JOIN / IS NULL 或 NOT IN 而不是 NOT EXISTS。

    使用NOT IN 重写的查询可能如下所示:

    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】:

      不知道是不是更快,你可以看看:

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

      假设 postid 永远不是 NULL / 一个不可为 NULL 的列。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多