[英]Confused on a somewhat complex LEFT/RIGHT JOIN query
感谢您抽时间阅读。
基本上我有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
现在这是我开始感到困惑的地方。 我猜想我需要在“关注”表上使用另一个JOIN语句,以便将返回结果限制为同时具有user_id和artist_id的“关注”条目的行。
即:
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
;
SELECT p.id,p.body,p.timecode,a.id AS artist_id,a.name
FROM Posts p
INNER JOIN Follows f ON p.artist_id = f.artist_id
INNER JOIN Artists a ON f.artist_id = a.id
WHERE f.user_id = X
还没有检查语法,我希望可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.