0

如果这个周末没有解决,这个(我的)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

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

任何的想法?提前谢谢。

4

1 回答 1

0

要在 MySQL 中模拟 FULL OUTER JOIN,您需要 UNION 外部连接到评论的帖子的结果,以及外部连接到帖子的评论 - 像这样:

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
于 2012-03-02T10:36:06.233 回答