2014-06-21 79 views
1

我試圖通過評論和喜歡的順序來顯示帖子。 有三個表使用此查詢評論
的表像它列是守值不像
如何按COUNT與多表的SUM和MINUS訂購

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

對每個計數使用派生表,下面的查詢計算每個帖子的評論,喜歡,unlikes,然後通過post_id將計數加入post表。

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