让我举例解释一下.请考虑下表:
Customer Id | Food
------------+---------
1 | Pizza
1 | Burger
1 | Hot Dog
2 | Milkshake
2 | Burger
3 | Pizza
我想删除那些从未订购过Pizza的客户的所有记录.所以,我应该留下这个(客户#2删除):
Customer Id | Food
------------+---------
1 | Pizza
1 | Burger
1 | Hot Dog
3 | Pizza
我知道我可以做一个NOT IN但性能很糟糕.
编写此查询以在sql Server中针对100,000条记录实现此目的的最高性能是什么?
一个简单的NOT EXISTS应该是
efficient和适当的索引.
DELETE c1 FROM Customers c1
WHERE NOT EXISTS
(
SELECT 1 FROM Customers c2
WHERE c1.[Customer Id] = c2.[Customer Id]
AND c2.[Food] = 'Pizza'
);
Demo
在[Customer Id]上创建索引,在Food上创建非聚集索引.