【发布时间】:2014-06-27 17:48:38
【问题描述】:
我有 4 张桌子:posts、users、mentions、following
posts
----------------------------
id | user_id | post_text
1 1 foo
2 1 bar
3 2 hello
4 3 jason
users
------------
id | name
1 jason
2 nicole
3 frank
mentions
--------------------------
id | post_id | user_id
1 4 1
following
-------------------------------------------------
id | user_id | user_id_of_user_being_followed
1 1 2
posts 包含发布一些文本的用户的 user_id
users 有用户 id 和用户名
mentions 拥有提及 1 个或多个其他用户的任何帖子的帖子 ID 和用户 ID
following 有一个用户 id 和他们关注的用户(用户可以关注 0 到多个用户)
我要做的是返回给定用户关注的用户的所有帖子,加上任何提到该用户的帖子(无论给定用户是否关注),而不返回任何重复项。
SELECT p.id, p.post, u.name,
FROM following f
JOIN posts p ON f.following = p.user_id
JOIN users u ON u.id = p.user_id
WHERE f.user_id = :user;
上面返回给定用户正在关注的用户的所有帖子,但我正在努力弄清楚如何包含提及(请记住,用户不必关注某人才能看到他们的帖子'中提到过)。
更新: 感谢 John R,我能够弄清楚这一点:
SELECT DISTINCT(p.id), p.post, u.name
FROM posts p
LEFT JOIN following f ON f.following = p.user_id
LEFT JOIN mentions m ON m.posts_id = p.id
JOIN users u ON u.id = p.user_id
WHERE (f.user_id = :user_id OR m.user_id = :user_id)
【问题讨论】:
标签: mysql