我在2个不同的数据库中有一个表。 DataBase1中的Table1和database2中的Table2。
Table1和Table2具有相同的列,具有不同的行内容。
每行对应一个宗地号码(TShipping_Tracking或TShipping_Reference或TShipping_OrderRef或TShipping_Barcode)和一个ID(TShipping_ID)。 Remarque:对于每个宗地(行),上面列出的与地块编号相关的4列中只有1列不为空
这些是每个数据库中表的架构:
create table Database1..Table1 (TShipping_ID varchar(50),TShipping_Tracking varchar(50),TShipping_Reference varchar(50),TShipping_OrderRef varchar(50),TShipping_Barcode varchar(50))
create table Database2..Table2 (TShipping_ID varchar(50),TShipping_Tracking varchar(50),TShipping_Reference varchar(50),TShipping_OrderRef varchar(50),TShipping_Barcode varchar(50))
此外,我有表Database1..Reject具有与Table1相同的列(和Table2)exept TShipping_ID:
create table Database1..Table3(TShipping_Tracking varchar(50),TShipping_Reference varchar(50),TShipping_OrderRef varchar(50),TShipping_Barcode varchar(50))
我想要检索Database1中不存在的宗地的TShipping_ID
我做了以下查询,但响应时间非常糟糕:
select isnull(isnull(isnull(D2t1 .TShipping_ID,D2t2.TShipping_ID),D2t3.tshipping_id),D2t4.tshipping_id) as TShipping_ID
from Database1..Table3 D1t3
left join Database1..Table1 D1t1 on D1t3.TShipping_tracking=D1t1.TShipping_tracking
left join Database1..Table1 D1t2 on D1t3.TShipping_Reference=D1t2.TShipping_Reference
left join Database1..Table1 D1t3 on D1t3.TShipping_OrderRef=D1t3.TShipping_OrderRef
left join Database1..Table1 D1t4 on D1t3.TShipping_barcode=D1t4.TShipping_barcode
left join Database2..Table2 D2t1 on D1t3.TShipping_tracking=D2t1.TShipping_tracking
left join Database2..Table2 D2t2 on D1t3.TShipping_Reference=D2t2.TShipping_Reference
left join Database2..Table2 D2t3 on D1t3.TShipping_OrderRef=D2t3.TShipping_OrderRef
left join Database2..Table2 D2t4 on D1t3.TShipping_barcode=D2t4.TShipping_barcode
where D1t1.TShipping_Tracking is null and D1t2.TShipping_Reference is null and D1t3.TShipping_OrderRef is null and D1t4.TShipping_BarCode is null
有没有人有更好的方法呢?
由于
答案 0 :(得分:0)
假设Table1.TShipping_ID
是NOT NULL
字段:
SELECT t2.TShipping_ID
FROM Table3 t3
LEFT JOIN Table2 t2
ON t2.TShipping_Tracking = t3.TShipping_Tracking
OR t2.TShipping_Reference = t3.TShipping_Reference
OR t2.TShipping_OrderRef = t3.TShipping_OrderRef
OR t2.TShipping_Barcode = t3.TShipping_Barcode
LEFT JOIN Table2 t1
ON t1.TShipping_Tracking = t3.TShipping_Tracking
OR t1.TShipping_Reference = t3.TShipping_Reference
OR t1.TShipping_OrderRef = t3.TShipping_OrderRef
OR t1.TShipping_Barcode = t3.TShipping_Barcode
WHERE t1.TShipping_ID IS NULL
这仍然会很慢,因为它非常接近CROSS JOIN
,但是你没有提供足够的信息来表明你正在做什么或者表格的关键字段是什么让我认为您可以在加入条件中将OR
替换为AND
。但我怀疑可能是这种情况。