SQL:如何包含不存在的记录

时间:2018-03-13 17:39:54

标签: mysql sql pivot-table

我正在进行查询,我按照upvotes对帖子进行排序。我有表postsvotes(post_id, user_id, vote),其中vote可以是1或-1。所以现在我的问题是,如果帖子没有任何upvotes,它根本不会显示在结果中。
我的问题:

SELECT P.* FROM `vicoteka-api`.posts P
INNER JOIN (
    SELECT post_id, COUNT(*) vote_count FROM `vicoteka-api`.votes 
    WHERE vote = 1 GROUP BY post_id
) V ON P.id = V.post_id
ORDER BY V.vote_count DESC

如何添加votes数据透视表中不存在的帖子?

3 个答案:

答案 0 :(得分:2)

使用left joincoalesce来获得没有投票的帖子。

SELECT P.*,COALESCE(v.vote_count,0) as vote_count 
FROM `vicoteka-api`.posts P
LEFT JOIN (SELECT post_id, COUNT(*) vote_count 
           FROM `vicoteka-api`.votes 
           WHERE vote = 1
           GROUP BY post_id
           ) V ON P.id = V.post_id
ORDER BY vote_count DESC

答案 1 :(得分:0)

Vamsi的回答是正确的。如果考虑性能,您可能希望将其与以下内容进行比较:

SELECT P.*, COUNT(v.post_id) as vote_count 
FROM vicoteka-api.posts P LEFT JOIN
     vicoteka-api.votes v
     ON P.id = V.post_id AND v.vote = 1
GROUP BY p.id
ORDER BY vote_count DESC;

或者甚至可能更好:

SELECT p.*,
       (SELECT COUNT(*)
        FROM vicoteka-api.votes v
        WHERE P.id = V.post_id AND v.vote = 1
       ) as vote_count 
FROM vicoteka-api.posts p 
ORDER BY vote_count DESC;

后两者允许将索引用于JOIN。最后一个甚至可以节省GROUP BY的费用。

答案 2 :(得分:0)

SELECT P.*, V.POST_ID, V_COUNT, VOTE_COUNT FROM `vicoteka-api`.posts P
RIGHT OUTER JOIN (
SELECT post_id, COUNT( NVL(vote_count),0) AS V_COUNT, VOTE_COUNT
FROM `vicoteka-api`.votes 
GROUP BY post_id, vote_count
) V ON P.id = V.post_id and V.vote_count <> -1
ORDER BY V.vote_count DESC

如果我错了,请纠正我。