简体   繁体   中英

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?

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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