我有2个mysql表“users1”和“users2”。它们都有以下字段
users1: email, zipcode, first_name, last_name, processed
users2: email, zipcode, first_name, last_name
我有以下SQL查询:
SELECT zipcode FROM users1 WHERE processed IS NOT NULL
目前此查询返回users1表的结果。但是,在返回结果之前,我想检查一下“zipcode”是否存在于users2表中。
所以基本上,如果“users2”中不存在“users1”的返回邮政编码,则只需返回结果
知道我该怎么做吗?
由于
答案 0 :(得分:1)
您可以使用NOT IN
:
SELECT zipcode
FROM users1
WHERE processed IS NOT NULL
AND zipcode NOT IN
(SELECT distinct zipcode from users2)
答案 1 :(得分:1)
使用外部联接筛选仅获取另一个表中不存在的行:
SELECT u1.zipcode
FROM users1 u1
LEFT JOIN users2 u2 ON u2.zipcode = u1.zipcode
WHERE processed IS NOT NULL
AND u2.zipcode IS NULL
答案 2 :(得分:0)
尝试这个未经测试的查询:
select user2.zipcode from user2 where user2.zipcode not in (SELECT zipcode FROM users1 WHERE processed IS NOT NULL)