是否有更快的方法在名为OrderDtl的表上编写以下查询?
OrderId Product
1 ORANGE
1 APPLE
2 SHAMPOO
2 SOAP
2 TOOTHPASTE
SELECT *
FROM OrderDtl
WHERE OrderId in
(
SELECT OrderId
FROM OrderDtl
WHERE Product='APPLE'
)
结果是
1 ORANGE
1 APPLE
答案 0 :(得分:5)
加入桌子。
看到Dems的评论后,我更改了SQL以添加几个索引:
CREATE TABLE #OrderDtl (OrderId INT, Product CHAR(10))
CREATE CLUSTERED INDEX IX_Order ON #OrderDtl (OrderId)
CREATE NONCLUSTERED INDEX IX_Order_Product ON #OrderDtl (Product) INCLUDE (OrderId)
INSERT #OrderDtl SELECT 1, 'ORANGE'
INSERT #OrderDtl SELECT 1, 'APPLE'
INSERT #OrderDtl SELECT 2, 'SHAMPOO'
INSERT #OrderDtl SELECT 2, 'SOAP'
INSERT #OrderDtl SELECT 2, 'TOOTHPASTE'
SELECT T2.*
FROM #OrderDtl T1 INNER JOIN #OrderDtl T2
ON T1.OrderId = T2.OrderId
WHERE T1.Product='APPLE'
SELECT *
FROM #OrderDtl
WHERE OrderId in
(
SELECT OrderId
FROM #OrderDtl
WHERE Product='APPLE'
)
比较生成的执行计划很有意思,对于这个简单的例子,结果是相同的:
修改强> 添加esastincy答案的执行计划,在执行“努力”中再次相同
您可能也对这篇文章感兴趣:SQL Server: JOIN vs IN vs EXISTS - the logical difference
答案 1 :(得分:0)
SELECT ord2.*
FROM OrderDtl ord1 INNER JOIN OrderDt1 ord2
ON ord1.Product = 'APPLE' AND ord2.OrderId = ord1.OrderId