有没有更好的方法来编写以下查询以优化性能。
INSERT INTO [dbo].[MBQ_All] ([Uniq], [StoreClass], [Store], [code], [ExtendedDescription], [ITEM_CLASS], [SUPPLIER], [Brands], [Min], [Max],[ADS]
,[Store+whMBQ])
SELECT [Uniq], [StoreClass], [Store], [code], [ExtendedDescription], [ITEM_CLASS], [SUPPLIER], [Brands], [Min], [Max],[ADS]
,[Store+whMBQ]
FROM dbo.MBQ_All_1
WHERE MBQ_All_1.Uniq NOT IN (
SELECT UNIQ
FROM dbo.MBQ_All
);
表格 MBQ_All 有超过4,00,000行,而 MBQ_All_1 有2,00,000行。
我正在使用SQL Server 2008。
答案 0 :(得分:2)
也许尝试使用NOT EXISTS:
INSERT INTO [dbo].[MBQ_All] ([Uniq], [StoreClass], [Store], [code], [ExtendedDescription], [ITEM_CLASS], [SUPPLIER], [Brands], [Min], [Max],[ADS]
,[Store+whMBQ])
SELECT [Uniq], [StoreClass], [Store], [code], [ExtendedDescription],
[ITEM_CLASS], [SUPPLIER], [Brands], [Min], [Max],[ADS] ,[Store+whMBQ]
FROM dbo.MBQ_All_1
WHERE NOT EXISTS (SELECT *
FROM dbo.MBQ_All
WHERE dbo.MBQ_All.UNIQ = MBQ_All_1.Uniq)
答案 1 :(得分:2)
MERGE陈述的明显案例:
MERGE [dbo].[MBQ_All] Tgt
USING [dbo].[MBQ_All_1] Src ON Tgt.Uniq = Src.Uniq
WHEN NOT MATCHED THEN
INSERT ( [Uniq], [StoreClass], [Store], [code], [ExtendedDescription], [ITEM_CLASS], [SUPPLIER], [Brands], [Min], [Max], [ADS], [Store+whMBQ])
VALUES (Src.[Uniq], Src.[StoreClass], Src.[Store], Src.[code], Src.[ExtendedDescription], Src.[ITEM_CLASS], Src.[SUPPLIER], Src.[Brands], Src.[Min], Src.[Max], Src.[ADS], Src.[Store+whMBQ]);
答案 2 :(得分:1)
其中一个选择是LEFT JOIN,但我不确定它是否会更快:
INSERT INTO [dbo].[MBQ_All]
([Uniq], [StoreClass], [Store], [code], [ExtendedDescription], [ITEM_CLASS], [SUPPLIER], [Brands], [Min], [Max],[ADS] ,[Store+whMBQ])
SELECT [Uniq], [StoreClass], [Store], [code], [ExtendedDescription], [ITEM_CLASS], [SUPPLIER], [Brands], [Min], [Max],[ADS]
,[Store+whMBQ]
FROM dbo.MBQ_All_1 mbqN
LEFT JOIN MBQ_All mbqO ON mbqN.Uniq = mbqO.Uniq
WHERE mbqO.Uniq IS NULL