使用SQL在共享博客中获取用户帖子和/或评论

时间:2012-03-02 09:22:54

标签: sql android-activity comments blogs posts

这个(我的)SQL问题会让我疯狂,如果在本周末没有解决的话!

一个简单的共享博客(意味着许多作者贡献)。让我们考虑一下我的数据库中的两个表:

帖子

  • ID
  • AUTHOR_ID
  • 标题
  • 含量

评论

  • ID
  • AUTHOR_ID
  • POST_ID
  • 含量

目标:我想显示贡献者的所有活动(=>固定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

看起来不错,但它没有给我用户创建帖子的行,但没有评论。

有什么想法吗? 提前完成。

1 个答案:

答案 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