将JOIN查询重写为子查询,缺少行?

时间:2018-09-17 00:50:58

标签: mysql subquery

我有以下MySQL查询返回这些行:

SELECT p.ID AS id, p.post_title AS title, p.post_author AS uid, SUM(v.pageviews) AS pageviews, IFNULL(c.comment_count, 0) AS comment_count 
FROM `views` v 
LEFT JOIN `posts` p ON v.postid = p.ID 
LEFT JOIN (SELECT comment_post_ID, COUNT(comment_post_ID) AS comment_count FROM `comments` WHERE comment_date_gmt > DATE_SUB('2018-08-16 18:34:46', INTERVAL 29 DAY) AND comment_approved = 1 GROUP BY comment_post_ID) c ON p.ID = c.comment_post_ID 
WHERE 1 = 1 AND p.post_type IN('post') AND v.view_datetime > DATE_SUB('2018-08-16 18:34:46', INTERVAL 29 DAY) AND p.post_password = '' AND p.post_status = 'publish' GROUP BY v.postid ORDER BY pageviews DESC LIMIT 5 OFFSET 0;

JOIN query

我目前正在尝试使用子查询而不是JOIN重写它,以检查性能是否更好。

以下查询返回的结果相同(comment_count列除外,因为我们只查询两个表而不是三个表):

SELECT p.ID AS id, p.post_title AS title, p.post_author AS uid, v.pageviews AS pageviews 
FROM `posts` p,
    (SELECT SUM(pageviews) AS pageviews, postid FROM `views` WHERE view_datetime > DATE_SUB( '2018-08-16 18:34:46', INTERVAL 29 DAY) GROUP BY postid) v
WHERE 1 = 1 AND p.ID = v.postid AND p.post_type IN('post') AND p.post_password = '' AND p.post_status = 'publish' GROUP BY v.postid ORDER BY pageviews DESC LIMIT 5 OFFSET 0

subqueries query

但是,如果我将comments表添加到组合中,则没有评论的帖子将被自动排除(例如ID为2956且具有3100个视图的帖子),与原始查询:

SELECT p.ID AS id, p.post_title AS title, p.post_author AS uid, v.pageviews AS pageviews, IFNULL(c.comment_count, 0) AS comment_count 
FROM `posts` p,
    (SELECT SUM(pageviews) AS pageviews, postid FROM `views` WHERE view_datetime > DATE_SUB( '2018-08-16 18:34:46', INTERVAL 29 DAY) GROUP BY postid) v,
    (SELECT COUNT(comment_post_ID) AS comment_count, comment_post_ID FROM `comments` WHERE comment_date_gmt > DATE_SUB('2018-08-16 18:34:46', INTERVAL 29 DAY) AND comment_approved = 1 GROUP BY comment_post_ID) c 
WHERE 1 = 1 AND p.ID = v.postid AND v.postid = c.comment_post_ID AND p.post_type IN('post') AND p.post_password = '' AND p.post_status = 'publish' GROUP BY v.postid ORDER BY pageviews DESC LIMIT 5 OFFSET 0

subqueries query with comments table

我对这方面的东西还没有真正的经验(如您所知),因此非常感谢任何帮助/提示以了解正在发生的事情。

1 个答案:

答案 0 :(得分:1)

正如我在评论中提到的那样,您的新查询仍然具有JOIN。如果您想使用子查询来测试性能,则需要将查询更改为类似的内容(这是我对原始工作查询的最佳猜测;在没有看到表结构和数据的情况下,很难百分百确定):

SELECT id, post_title AS title, post_author AS uid, 
    (SELECT SUM(pageviews) 
     FROM views v 
     WHERE v.postid = posts.id AND 
           v.view_datetime > DATE_SUB('2018-08-16 18:34:46', INTERVAL 29 DAY)
    ) AS pageviews,
    (SELECT COUNT(comment_post_ID) 
     FROM comments c 
     WHERE c.comment_post_ID = posts.id AND
           c.comment_date_gmt > DATE_SUB('2018-08-16 18:34:46', INTERVAL 29 DAY) AND 
           c.comment_approved = 1
    ) AS comment_count
FROM posts
WHERE p.post_type IN('post') AND p.post_password = '' AND p.post_status = 'publish'
ORDER BY pageviews DESC 
LIMIT 5 OFFSET 0;