简体   繁体   English

从两个表中选择不匹配的记录,并在第二个表上使用过滤器

[英]Select unmatched records from two tables with a filter on second table

I have 2 mysql tables a and b.我有 2 个 mysql 表 a 和 b。 I need to show all records in a that are not in b using a common column 'ID'.我需要使用公共列“ID”显示 a 中不在 b 中的所有记录。 Normally this is pretty straight forward but my problem here is this: I need to put a where clause on table b because I'm not interested in all unmatched records just the ones that meet the table 2 where clause criterion:通常这很简单,但我的问题是:我需要在表 b 上放置一个 where 子句,因为我对所有不匹配的记录不感兴趣,只是那些满足表 2 where 子句标准的记录:

SELECT a.ID, a.Description 
FROM a 
LEFT JOIN b ON a.ID = b.ID 
WHERE a.Inactive = 0 
AND b.Room = '101' 
AND b.ID Is Null

This returns nothing.这不返回任何内容。 However if I remove the AND b.Room = '101' part, it displays the expected results.但是,如果我删除AND b.Room = '101'部分,它会显示预期的结果。 But I need that condition because I need only unmatched records specific to a 'room' and not all unmatched records但我需要这个条件,因为我只需要特定于“房间”的不匹配记录,而不是所有不匹配的记录

Move the conditions involving table b from WHERE to ON clause:将涉及表b的条件从 WHERE 移动到 ON 子句:

SELECT a.ID, a.Description 
FROM a 
LEFT JOIN b ON a.ID = b.ID AND b.Room = '101' 
WHERE a.Inactive = 0 
AND b.ID Is Null

It'll find rows where a does not have a match in b (id matches and room number = 101).它将查找 a 在 b 中没有匹配项的行(id 匹配房间号 = 101)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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