简体   繁体   English

困惑于一个稍微复杂的LEFT / RIGHT JOIN查询

[英]Confused on a somewhat complex LEFT/RIGHT JOIN query

thanks for taking the time to read this. 感谢您抽时间阅读。

Essentially I have 3 tables. 基本上我有3张桌子。 Posts, Follows, Artists. 帖子,关注者,艺术家。 What I am trying to do is pull all the 'Posts' from 'Artists' that the user 'Follows'. 我想做的是从用户“关注”的“艺术家”中提取所有“帖子”。 I am passing the user_id in, and trying to pull data from 'Posts' and 'Artists' 我传入了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

So, my basic query starts out like this: 因此,我的基本查询如下所示:

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

Now this is where I start to get confused. 现在这是我开始感到困惑的地方。 I am guessing that I need another JOIN statement on the "Follows" table so that I limit the returned results to rows that have a "follows" entry with both the user_id and artist_id. 我猜想我需要在“关注”表上使用另一个JOIN语句,以便将返回结果限制为同时具有user_id和artist_id的“关注”条目的行。

ie: 即:

RIGHT JOIN Follows
ON Posts.artist_id = Follows.artist_id
WHERE Follows.user_id = :userid

My problem is that I'm not really even sure how to write this properly, although I feel like i'm on the right track here... sorta 我的问题是,尽管我觉得自己在正确的轨道上,但我什至不确定如何正确编写此代码……

ANY help would be much appreciated!!! 任何帮助将非常感激!!! Thanks. 谢谢。

EDIT Please note I am pulling data from both the Posts and Artists tables, not just the Posts table. 编辑请注意,我正在从Posts和Artists表中提取数据,而不仅是Posts表。 Not sure if this makes a big difference. 不知道这是否有很大的不同。

I can't see that you need an outer join, standard SQL inner joins should return the set you want. 我看不到您需要外部联接,标准SQL内部联接应返回所需的集合。 You have to trust SQL to go find all the rows you're interested in. 您必须信任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

Haven't checked the syntax I hope it is ok. 还没有检查语法,我希望可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM