I don’t know where else to ask. I have this query:
SELECT po.* FROM posts po, follows f, user pn
WHERE (f.follower_id = #{id}
AND f.followed_id = pn.id
AND po.user_id = pn.id)
OR (po.user_id = #{id})
ORDER BY created_at DESC LIMIT 10 OFFSET #{offset}
I get the posts from the followers correctly, but not the posts by the user himself. It seems as if the second part of the OR is always ignored.
SELECT * FROM posts WHERE user_id = #{id}
works fine, though.
EDIT
I am sorry, I accidentally hit enter before I was done with the text!!
EDIT 2
This now seems to work:
SELECT DISTINCT po.* FROM users pn
INNER JOIN follows f ON f.follower_id = #{id}
INNER JOIN posts po ON po.user_id = f.followed_id OR po.user_id = #{id}
ORDER BY created_at DESC LIMIT 10 OFFSET #{offset}
Maybe someone can tell me why?
Try this:
The implicit joins were not being considered in the second case. This is one of the reasons I shy away from implicit joins, instead using explicit
INNER JOINclauses.If this doesn’t get the results you are looking for, you might need to consider a
UNIONinstead. Your description is a bit vague and you have not given us your schema, so I can’t tell if this query will work or not.