如何选择数据库中有喜欢的所有帖子。而且我也希望所有不喜欢的帖子都列在同一个SQL-Query中。喜欢的内容存储在一个表中,每个表都连接到一个带有外键的帖子
SELECT likes.*, posts. * , profile . *, credentials.username, posts.session_sessionid as sSession
FROM likes, posts, follows, profile, credentials
WHERE follows.users = posts.userId
AND profile.userId= follows.users
AND profile.userId = credentials.profle_userId
AND posts.session_sessionId IS NOT NULL
AND likes.idposts = posts.idposts ORDER BY posts.date DESC`
答案 0 :(得分:3)
请改用outer join
。如果要将like count
添加到结果中,一个选项是使用另一个子查询来获取count
:
SELECT likes.*, t.likecount, posts.* ,profile.*, credentials.username,
posts.session_sessionid as sSession
FROM posts
join follows on follows.users = posts.userId
join profile on profile.userId= follows.users
join credentials on profile.userId = credentials.profle_userId
left join likes on likes.idposts = posts.idposts
left join (
select idposts, count(*) likecount
from likes
group by idposts
) t on t.idposts = posts.idposts
WHERE posts.session_sessionId IS NOT NULL
ORDER BY posts.date DESC`
一般情况下,我不建议在from
子句中使用逗号。