我试图仅消除两个字段与另一个表中给定值匹配的记录。
SELECT CODE, NUM
FROM TABLE_A
WHERE (CODE not in (SELECT CODE FROM TABLE_B) AND NUM not in (SELECT NUM FROM TABLE_B))
然而,这似乎消除了具有这些值之一的所有记录。我只需要消除两个都匹配TABLE2给定记录的记录。 OR在这里看似违反直觉吗?
答案 0 :(得分:0)
SELECT CODE, NUM
FROM TABLE_A TA
WHERE
not exists (select 1 from TABLE_B TB where TB.CODE=TA.CODE)
and
not exists (select 1 from TABLE_B TB where TB.NUM=TA.NUM)
答案 1 :(得分:0)
SELECT CODE, NUM
FROM TABLE_A a
WHERE NOT EXISTS (SELECT 1 FROM TABLE_B b where b.CODE = a.CODE and b.NUM = a.NUM);
EXISTS关键字测试子查询中是否存在任何行。 如果没有找到行,则答案为FALSE。否则,子查询 返回TRUE。 NOT EXISTS反转结果。
答案 2 :(得分:0)
如果您担心NOT EXISTS的性能,您还可以尝试使用LEFT OUTER JOIN和WHERE子句检查相同的条件:
SELECT
a.CODE,
a.NUM
FROM
TABLE_A a
LEFT OUTER JOIN -- return all from table A, and matches from table B
TABLE_B b ON
a.CODE = b.CODE AND
a.NUM = b.NUM
WHERE b.CODE IS NULL -- filter out the ones that matched; think of this as a reverse INNER