我有两个表都有fname和lname列我将如何编写查询以检查其中一个表是否缺少另一个表中不存在的记录?
这是表及其列
tbl_client
-fname
-lname
tbl_lease
-fname
-lname
我需要继续检查tbl_lease以查看记录是否与表tbl_client匹配,如果没有,我将能够显示给我。感谢
答案 0 :(得分:1)
一种简单的方法是在not exists
子句中使用where
谓词:
select tbl_client.fname, tbl_client.lname, 'missing from lease' as missingfrom
from tbl_client
where not exists
(select 1 from tbl_lease where tbl_lease.fname=tbl_client.fname
and tbl_lease.lname=tbl_client.lname)
union
select tbl_lease.fname, tbl_lease.lname, 'missing from client' as missingfrom
from tbl_lease
where not exists
(select 1 from tbl_client where tbl_lease.fname=tbl_client.fname
and tbl_lease.lname=tbl_client.lname)
或者也许做一个完整的外连接并检查哪个表的记录为空,但这可能不那么简单,而且效率可能低于not exists
。
答案 1 :(得分:0)
获取tbl_client中不存在fname的tbl_lease中的所有记录:
select tl.* from tbl_lease tl
left join tbl_client tc on tl.fname = tc.fname
where tc.fname is null;
反过来说,tbl_client中存在的记录,其中fname不存在于tbl_lease中
select tc.* from tbl_client tc
left join tbl_lease tl on tc.fname = tl.fname
where tl.fname is null;