Get user Posts and/or Comments in a sharing blog using SQL

浪尽此生 提交于 2019-12-12 03:17:19

问题


This (My)SQL problem will make me crazy if not solved this week-end!

A simple shared blog (means many authors contribute). Let's consider that two tables on my database:

Posts:

  • id
  • author_id
  • title
  • content

Comments:

  • id
  • author_id
  • post_id
  • content

Goal: I want to display all the activities of a contributor (=> fixed author_id). What I mean by activity is:

  • If the user created the post and commented: Display the post title and the user comment
  • If the user created the post but doesn't comment: Display only post title
  • If the user didn't create the post, but commented: Display the post title and the user comment

I tried this SQL Script:

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

Looks fine, but it doesn't give me the row where the user created the post, but doesn't comment.

Any idea? Thanx in advance.


回答1:


To simulate FULL OUTER JOIN in MySQL, you need to UNION the results of Posts outer joined to Comments, with those of Comments outer joined to Posts - like so:

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


来源:https://stackoverflow.com/questions/9530760/get-user-posts-and-or-comments-in-a-sharing-blog-using-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!