如何通过COUNT与多表的SUM和MINUS进行排序

时间:2014-06-21 22:34:44

标签: php mysql

我正试图通过评论和喜欢的顺序来显示帖子。 此查询中有三个表格使用帖子评论
对于表格来说,它有类型列,保持值不像

SQL

SELECT (SELECT COUNT(id) AS count_comment 
FROM comment WHERE comment.post_id = post.post_id),
       (SELECT COUNT(id) AS count_like 
FROM like WHERE like.post_id = post.post_id AND like.type = 'like'),
       (SELECT COUNT(id) AS count_unlike 
FROM like WHERE like.post_id = post.post_id AND like.type = 'unlike'),
       post.* FROM post
       ORDER BY (count_comment + count_like - count_unlike) DESC;

所以,这是一个在页面上显示的例子

post_id | comment | like | unlike | (comment+like-unlike)
4       | 5       | 3    | 1      |  7
1       | 2       | 3    | 0      |  5 
2       | 1       | 1    | 4      | -2 
...     | ...     | ...  | ...    | ...

我的问题是我的SQL很慢,请提出另一种方法,如果可以的话。我试过使用JOIN,但我无法弄清楚它的SQL应该是什么,请帮忙谢谢。

1 个答案:

答案 0 :(得分:1)

对每个计数使用派生表,下面的查询计算每个帖子的评论,喜欢,不喜欢,然后通过post将计数加到post_id表。

SELECT 
    p.post_id,
    COALESCE(c.comment_count,0) comment_count,
    COALESCE(l.like_count,0) like_count,
    COALESCE(ul.unlike_count,0) unlike_count,
    (COALESCE(c.comment_count,0) 
       + COALESCE(l.like_count,0) 
       - COALESCE(ul.unlike_count,0)) total
FROM post p
LEFT JOIN (
    SELECT c.post_id,
    COUNT(*) comment_count
    FROM comment c
    GROUP BY c.post_id
) c ON c.post_id = p.post_id
LEFT JOIN (
    SELECT l.post_id,
    COUNT(*) like_count
    FROM like l
    WHERE l.type = 'like'
    GROUP BY l.post_id
) l ON l.post_id = p.post_id
LEFT JOIN (
    SELECT ul.post_id,
    COUNT(*) unlike_count
    FROM like ul
    WHERE ul.type = 'unlike'
    GROUP BY ul.post_id
) ul ON ul.post_id = p.post_id
ORDER BY total DESC