开发者

Confused on a somewhat complex LEFT/RIGHT JOIN query

开发者 https://www.devze.com 2023-03-14 21:17 出处:网络
thanks for taking the time to read this. Essentially I have 3 tables. Posts, Follows, Artists. What I am trying to do is pull all the \'Posts\' from \'Artists\' that the user \'Follows\'. I am passi

thanks for taking the time to read this.

Essentially I have 3 tables. 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'

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 sta开发者_Python百科rts 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.

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. 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. You have to trust SQL to go find all the rows you're interested in.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消