如何返回第二个表中不存在或存在'null'值的所有内容



T1:

ID   NAME
132  TOM
133  JEK
134  MAX
135  JIZ

T2:

ID      VALUE      CID
1       house      132
2       flat       133
3       'null'     135

来自T1的ID=T2 中的CID

我需要返回所有在T2中没有记录或有记录但带有'null的NAMES;VALUE列中。我试过这个:

选择T1.名称,T2.值从T1加入T2在T1.ID=T2.CID上其中T2.value=‘完整’

如果记录存在并且具有null值,这很好,但我还需要返回T2中没有记录的所有记录,我如何自定义/更改我的查询?

一种方法是外部联接表并返回t1的行,其中t2为空

select t1.*
from t1
left join t2 on t2.cid=t1.id and t2.value is not null
where t2.id is null

如果您希望t1中的记录不在t2中,请考虑not exists:

select t1.*
from t1
where not exists (select 1 from t2 where t2.cid = t.id);

如果您想要任何不值为'null'的行,您可以使用:

select t1.*
from t1
where not exists (select 1
from t t2
where t2.cid = t.id and t2.value <> 'null'
);

最新更新