pet*_*hka 2 mysql performance not-exists
我有两个表的帖子和评论。表注释具有post_id属性。我需要把所有 的帖子,类型为“开放”,对此有没有意见类型为“好”和创建日期5月1日。
使用这样的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')
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我不确定NOT EXISTS是否是完美的构造。
您是对的-您可以做得更好。有关详细信息,请参阅Quassnoi的这篇文章,但结论是:
这就是为什么在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')
Run Code Online (Sandbox Code Playgroud)