我在进行查询时遇到麻烦,给定一个包含帖子的表和一个包含帖子投票的表,其中帖子投票包含帖子的 ID 和投票类型(“UP”或“DOWN”),输出“的数量”每个帖子的“UP”票和“DOWN”票。
我尝试使用 View 执行以下查询:
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 票“赞成”票和 1 票“反对”票时,否则它不会考虑它。我发现问题出在U和D View 中,其中0票的记录没有放入 View 中。
知道如何解决吗?
最佳答案
假设 postvotes 表仅包含至少有一个赞成票或反对票的帖子,您可以尝试下面的查询。
--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)
关于mysql - COUNT(*) 为 0 时不包含在结果中并且连接时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38558199/