andrewtweber
andrewtweber

Reputation: 25529

LEFT JOIN with a condition

I need to join two tables. I only want to show matches where users.private = 0

feeds
id     user_id
100    1
101    NULL
102    2

users
id   private
1    1
2    0

I have seen many related questions, and the answer is always to move the WHERE condition into ON instead. But if i do this:

SELECT `feeds`.`id`, `feeds`.`user_id` AS `feed_user_id`, `users`.`id` AS `user_id`,  `users`.`private` 
FROM  `feeds` 
    LEFT JOIN `users` ON `feeds`.`user_id` = `users`.`id` 
        AND `users`.`private` = 0

This returns

id     feed_user_id  user_id  private
100    1             NULL     NULL
101    NULL          NULL     NULL
102    2             2        0

What I WANT it to do is exclude the first row id 100. (So I guess that is not really a LEFT JOIN -> I want it to LEFT JOIN if the condition is met, otherwise exclude) How can I do this?

Upvotes: 0

Views: 282

Answers (1)

user1618143
user1618143

Reputation: 1748

You need two separate condition clauses, one on the JOIN and one on the SELECT, like so:

SELECT `feeds`.`id`, `feeds`.`user_id` AS `feed_user_id`, `users`.`id` AS `user_id`,  `users`.`private` 
FROM  `feeds` 
LEFT JOIN `users` ON `feeds`.`user_id` = `users`.`id` 
WHERE `users`.`private` = 0 OR `feeds`.`user_id' IS NULL

The problem with your current approach is that the join is treating private users as if they don't exist, rather than saying "this person exists and I should exclude this row from the results".

Upvotes: 1

Related Questions