当用户删除我刚设置的帖子或评论时,delete
列为1。
问题是,我使用计数向用户显示他在帖子上有多少评论。
select c.nome, p.foto, c.user, p.user, count(DISTINCT comentarios.id) as comentarios_count from posts p
join cadastro c on p.user=c.id
left join comentarios on comentarios.foto = p.id
where p.delete='0' and comentarios.delete='0'
group by p.id
order by p.id desc limit ?
问题是comentarios.delete =' 0'将仅选择至少有一条评论的帖子。我想选择所有帖子,但只计算delete
设置为0的评论。
怎么了?
答案 0 :(得分:1)
如何选择所有并只删除删除
select c.nome, p.foto, c.user, p.user, count(DISTINCT comentarios.id) -sum(comentarios.delete) as comentarios_count from posts p
join cadastro c on p.user=c.id
left join comentarios on comentarios.foto = p.id
where p.delete='0'
group by p.id
order by p.id desc limit ?
答案 1 :(得分:1)
您可以使用条件求和而不是计数,如下所示:
select c.nome, p.foto, c.user, p.user,
SUM(CASE comentarios.Deleted WHEN 0 THEN 1 ELSE 0 END)
as comentarios_count from posts p
join cadastro c on p.user=c.id
left join comentarios on comentarios.foto = p.id
where p.delete='0'
group by p.id
order by p.id desc limit ?
它将计算评论未删除,并且似乎比计算每个帖子的COUNT和SUM更快