这个(我的)SQL问题会让我疯狂,如果在本周末没有解决的话!
一个简单的共享博客(意味着许多作者贡献)。让我们考虑一下我的数据库中的两个表:
帖子:
评论:
目标:我想显示贡献者的所有活动(=>固定author_id)。我的意思是活动:
我试过这个SQL脚本:
SELECT p.id AS post_id, p.author_id AS post_author_id, c.author_id AS comment_author_id, title, c.content
FROM Posts p JOIN Comments c ON p.id = c.post_id
WHERE p.author_id = $userId
OR c.author_id = $userId
看起来不错,但它没有给我用户创建帖子的行,但没有评论。
有什么想法吗? 提前完成。
答案 0 :(得分:0)
要在MySQL中模拟FULL OUTER JOIN,你需要UNION将Posts外部的结果加入到Comments中,将那些注释外部加入到Posts中 - 就像这样:
SELECT p.id AS post_id,
p.author_id AS post_author_id,
c.author_id AS comment_author_id,
p.title,
c.content
FROM Posts p
LEFT JOIN Comments c ON p.id = c.post_id AND c.author_id = $userId
WHERE p.author_id = $userId
UNION ALL
SELECT p.id AS post_id,
p.author_id AS post_author_id,
c.author_id AS comment_author_id,
p.title,
c.content
FROM Posts p
RIGHT JOIN Comments c ON p.id = c.post_id
WHERE c.author_id = $userId