感谢您花时间阅读本文。
基本上我有 3 个表。帖子、关注、艺术家。我想做的是从用户“关注”的“艺术家”中提取所有“帖子”。我正在传递 user_id,并尝试从“帖子”和“艺术家”中提取数据
Posts /* the posts table */
id
body
artist_id
timecode
Follows /* the follows table */
id
artist_id
user_id
Artists /* the artists table */
id
name
所以,我的基本查询是这样开始的:
SELECT Posts.id,Posts.body,Posts.timecode,Artists.id AS artist_id,Artists.name
FROM Posts,Artists
LEFT JOIN Artists
ON Posts.artist_id = Artists.id
这就是我开始感到困惑的地方。我猜测我需要在“Follows”表上使用另一个 JOIN 语句,以便将返回的结果限制为具有包含 user_id 和 artist_id 的“follows”条目的行。
即:
RIGHT JOIN Follows
ON Posts.artist_id = Follows.artist_id
WHERE Follows.user_id = :userid
我的问题是我什至不确定如何正确地编写它,尽管我觉得我在这里走在正确的轨道上......有点
任何帮助将不胜感激!!!谢谢。
编辑 请注意,我正在从 Posts 和 Artists 表中提取数据,而不仅仅是 Posts 表。不确定这是否有很大的不同。
最佳答案
我看不出您需要外连接,标准 SQL 内连接应该返回您想要的集合。您必须信任 SQL 才能找到您感兴趣的所有行。
SELECT
p.*
FROM
posts p,
artists a,
follows f
WHERE
f.user_id = :userid AND
a.id = f.artist_id AND
p.artist_id = a.id
;
关于mysql - 对有点复杂的 LEFT/RIGHT JOIN 查询感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6462064/