如何优化以下查询?
DELETE FROM #Data
WHERE ID NOT IN (SELECT MIN(ID)
FROM #Data
GROUP BY SerialNumber, VendorName)
最多需要2分钟才能执行。
这是表结构:
CREATE TABLE #Data
(
ID INT IDENTITY (1, 1),
ItemSupplierKey INT NOT NULL,
SerialNumber VARCHAR(100) NOT NULL,
VendorName VARCHAR(50) NOT NULL
);
它包含257316条记录。
以下是此临时表的索引:
CREATE CLUSTERED INDEX PX_Data ON #Data (SerialNumber, VendorName);
CREATE INDEX IX_Data ON #Data (ID);
答案 0 :(得分:0)
您可以重写删除以使用left join
加入相同的#Data
表并删除已加入记录null
的位置:
delete d
from #Data d
left join (
SELECT MIN(ID) as ID FROM #Data GROUP BY SerialNumber, VendorName
) t1 on d.ID = t1.ID
where t1.ID is null
答案 1 :(得分:0)
使用common table expression
row_number()
时,您应该会看到性能提升:
WITH CTE AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY SerialNumber, VendorName ORDER BY ID) RN
FROM Data
)
DELETE FROM CTE WHERE RN != 1