我正在试图找出哪个更快,一个像“WHERE IN(SELECT 1 FROM MyTable)”这样的子句,或像“WHERE EXISTS(SELECT 1 FROM MyTable)”这样的子句。
让我们使用SqlServer文档中的查询:
SELECT * FROM Orders
WHERE ShipRegion = 'WA' AND EXISTS (
SELECT EmployeeID FROM Employees AS Emp
WHERE Emp.EmployeeID = Orders.EmployeeID)
或者
SELECT * FROM Order
WHERE ShipRegion = 'WA' AND EmployeeID IN (
SELECT EmployeeID FROM Employees AS Emp
WHERE Emp.EmployeeID = Orders.EmployeeID)
我想知道答案,如果有人有,但我真的想知道如何在SqlServer 2005中自己测试它。(我是SqlServer的菜鸟。)
谢谢!
答案 0 :(得分:3)
使用INNER JOIN会比子查询更快:
SELECT *
FROM Order o
INNER JOIN Employees e ON o.EmployeeID = e.EmployeeID
WHERE ShipRegion = 'WA'
或者使用特定标准:
SELECT *
FROM Order o
INNER JOIN Employees e ON o.EmployeeID = e.EmployeeID
WHERE ShipRegion = 'WA'
AND e.EmployeeID = 42
答案 1 :(得分:2)
要亲眼看看,您可以: 比较实际执行成本,运行
SET STATISTICS IO ON
SET STATISTICS TIME ON
然后运行两个查询
同时比较执行计划,突出显示两个查询并按Ctrl + L,您将看到计划。很可能你会看到相同的计划。
答案 2 :(得分:1)
您还可以删除WHERE
案例中的IN
子句:
SELECT * FROM Orders
WHERE ShipRegion = 'WA' AND EmployeeID IN (SELECT EmployeeID FROM Employees)
查询优化器应该能够为两个查询生成相同的执行计划。我会选择一个更具可读性的那个。
答案 3 :(得分:1)
sql子查询虽然相同但不会给你你正在寻找的答案,因为它是相关的,可以改成JOIN。
一般来说EXISTS()应该更快,因为它给出了结果,而不必在找到第一行后找到任何更多的关系,而IN()仍然必须找到 后续行直到完成。
因此
SELECT * FROM Orders
WHERE ShipRegion = 'WA' AND EXISTS (
SELECT 'x' FROM Employees AS Emp
WHERE Emp.EmployeeID = 42)
应该在
之前完成SELECT * FROM Order
WHERE ShipRegion = 'WA' AND EmployeeID IN (
SELECT EmployeeID FROM Employees AS Emp
WHERE Emp.EmployeeID = 42)