我有这个问题:
select
count(DISTINCT likes.user) as likes_count, //count likes
SUM(CASE comentarios.delete WHEN 0 THEN 1 ELSE 0 END) as comentarios_count from posts p //count comments (not deleted)
left join likes on likes.post = p.id
left join comentarios on comentarios.foto = p.id
group by p.id
计算一个帖子的喜欢和评论。我的输出错误,例如我有2个喜欢和3个评论,它会显示= 2个喜欢和6个评论。
我尝试在SUM(
之后添加DISTINCT,但它无效。有什么想法吗?
如果用户有2个喜欢 - 2个评论,则会显示: 2喜欢 - 4条评论
如果用户有2个喜欢 - 4个评论,则会显示: 2喜欢 - 8条评论
如果用户有2个喜欢 - 10个评论,则会显示: 2喜欢 - 20条评论
如果用户有4个喜欢 - 10个评论,则会显示: 4喜欢 - 40条评论
答案 0 :(得分:0)
也许你想要这个查询,而不是测试
select
SUM(CASE comentarios.delete WHEN 0 THEN 1*likes.user ELSE 0 END) as likes_count, //count likes
SUM(CASE comentarios.delete WHEN 0 THEN 1 ELSE 0 END) as comentarios_count from posts p //count comments (not deleted)
left join likes on likes.post = p.id
left join comentarios on comentarios.foto = p.id
group by p.id