当0和麻烦加入时,COUNT(*)不包含在结果中

时间:2016-07-25 00:27:12

标签: mysql sql

我在查询时遇到麻烦,给出一个包含帖子的表和一个包含postsvotes的表,其中postsvotes包含帖子的id和投票类型('UP'或'DOWN'),输出'的数量'每个帖子的UP'投票和'DOWN'投票。

我使用视图尝试了以下查询:

DROP VIEW P, U, D;
CREATE VIEW P AS SELECT p.id, p.title, p.content FROM posts as p, users as u WHERE u.id = p.userId GROUP BY p.id ORDER BY p.datetime DESC;
CREATE VIEW U AS SELECT count(*) as Uvotes, postId FROM postsvotes, posts WHERE posts.id = postsvotes.postId AND postsvotes.type = 'UP' GROUP BY postId;
CREATE VIEW D AS SELECT count(*) as Dvotes, postId FROM postsvotes, posts WHERE posts.id = postsvotes.postId AND postsvotes.type = 'DOWN' GROUP BY postId;
SELECT Uvotes, Dvotes, u.postId as postId FROM U, D WHERE u.postId = d.postId GROUP BY postId;

它有点有用,但只有当该帖子至少有1个'UP'投票和1个'DOWN'投票时,否则它不会考虑它。我发现问题出在U和D视图中,其中0票的记录没有放在视图中。

关于如何解决的任何想法?

2 个答案:

答案 0 :(得分:0)

假设postvotes table only 包含至少有一个upvote或downvote的帖子,你可以尝试下面的查询。

--Get upvote and downvote count for posts in the postvotes table
SELECT 
 postId
,count(case when type = 'UP' then 1 end) upvotes
,count(case when type = 'DOWN' then 1 end) downvotes
FROM postvotes 
GROUP BY postId
UNION ALL
--Get posts that have no votes at all
SELECT Id, 0, 0 
FROM posts p
WHERE NOT EXISTS (select 1 from postvotes where postId = p.Id)

答案 1 :(得分:0)

我想你只想要一个left join和聚合:

SELECT p.postId, 
       SUM(pv.type = 'UP') as Upvotes, 
       SUM(pv.type = 'DOWN') as Downvotes, 
FROM posts p LEFT JOIN
     postvotes pv
     ON p.postId = pv.postId
GROUP BY p.postId;