我必须得到所有帖子,即使他们在计数上有0个喜欢,但是那些无论如何都没有出现,我尝试了内连接,左外连接而没有
select
post.id as idPost,
post.data,
autor.nome as nome,
post.texto,
post.idAutor,
count(likes.idAutor) as numeroLikes
from post
join utilizador autor
on autor.id = post.idAutor
left join likes
on post.id = likes.idPost
left join amigos as a
on a.idAmigo2 = post.idAutor
where (post.idAutor = a.idAmigo2 and a.idAmigo1 = 3) or post.idAutor = 3
and idPost > 0
group by post.id~
这是帖子表,你可以看到ID 43
这是我发布的查询的结果,你可以看到它没有显示idPost 43的喜欢数量,因为它是0
答案 0 :(得分:2)
当您在where子句中避免使用likes
的值比较属性时,likes
上的左外连接应该有效。比较强制所有行在结果中具有likes
的非空值。您应该将idPost > 0
修改为(idPost is null or idPost > 0)
或将此比较移至approriate join子句中。
答案 1 :(得分:2)
这是一个不应该受帖子消失的问题,因为他们不喜欢:
SELECT
post.id as idPost,
COUNT(likes.idAutor) AS numeroLikes
FROM post
LEFT JOIN utilizador autor
ON autor.id = post.idAutor
LEFT JOIN likes
ON post.id = likes.idPost
LEFT JOIN amigos AS a
ON a.idAmigo2 = post.idAutor AND
((post.idAutor = a.idAmigo2 AND a.idAmigo1 = 3) OR
post.idAutor = 3)
WHERE idPost > 0
GROUP BY post.id
我对您的查询进行了三项重大更改:
WHERE
子句中的所有条件移动到ON
子句中,这样可以防止帖子被丢弃。