我在db1中有一个表t1
,在t2
中有另一个表db2
。我在两个表中都有相同的列。
如何只检索那些不在另一个表中的行?
select id_num
from [db1].[dbo].[Tbl1]
except
select id_num
from [db2].[dbo].[Tb01]
答案 0 :(得分:0)
您可以使用LEFT JOIN或WHERE NOT IN功能。
使用WHERE NOT IN:
select
dbase1.id_num from [db1].[dbo].[Tbl1] as dbase1
where dbase1.id_num not in
(select dbase2.id_num from [db2].[dbo].[Tb01] as dbase2)
使用LEFT JOIN(建议这样做要快得多)
SELECT dbase1.id_num
FROM [db1].[dbo].[Tbl1] as dbase1
LEFT JOIN [db2].[dbo].[Tb01] as dbase2 ON dbase2.id_num COLLATE Latin1_General_CI_A = dbase1.id_num COLLATE Latin1_General_CI_A
WHERE dbase2.id_num IS NULL
答案 1 :(得分:0)
将表与DB2进行比较其他数据库可能具有select a -b语句或类似语句。因为当时我的数据库也没有a-b我使用以下内容。将语句包装在create table语句中以挖掘结果。没有行和表是相同的。我已经在BEFORE | AFTER中添加了一栏,使结果易于阅读。
SELECT 'AFTER', A.* FROM
(SELECT * FROM &AFTER
EXCEPT
SELECT * FROM &BEFORE) AS A
UNION
SELECT 'BEFORE', B.* FROM
(SELECT * FROM &BEFORE
EXCEPT
SELECT * FROM &AFTER) AS B