MYSQL - Select only if row in LEFT JOIN is not present

孤者浪人 提交于 2020-08-19 11:17:09

问题


I have 2 simple mysql tables. The first 1 called mail and has 2 rows:

sender | receiver
Marley | Bob 
Saget  | Bob 

The second one called block and has 1 row:

blocker | blocked
  Bob   | Marley

I want to select sender(s) from the first table who sent Bob emails but aren't blocked in the block table. So the results should be:

sender 
 saget

I tried the following query but it's not returning results:

SELECT * FROM mail  
LEFT JOIN block ON (block.blocker = 'Bob') 
WHERE (block.blocked <> mail.sender)

回答1:


The left join will produce null rows for the mismatches.
It's those null rows that you need to filter on.

SELECT * FROM mail  
LEFT JOIN block ON (block.blocker = 'Bob') 
WHERE block.blocker IS NULL

It's kind of strangle to be joining on a fixed value however, a more common join (given your tables) would be:

SELECT * FROM mail  
LEFT JOIN block ON (block.blocker = mail.receiver
                and block.blocked = mail.sender)<<-- these should match
WHERE block.blocker IS NULL                     <<-- select only mismatches
AND mail.receiver like 'bob';



回答2:


Try this:

SELECT sender
FROM mail m
WHERE NOT EXISTS (SELECT 1 FROM block 
                  WHERE blocker = m.receiver 
                  AND blocked = m.sender)


来源:https://stackoverflow.com/questions/15532646/mysql-select-only-if-row-in-left-join-is-not-present

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!