sql server逻辑读取更多where where子句?

时间:2013-12-28 14:12:21

标签: sql sql-server sql-server-2008 sql-server-2008-r2

SELECT C.custid, C.companyname,
O.orderid, O.orderdate
FROM Sales.Customers AS C
INNER JOIN Sales.Orders AS O
ON C.custid = O.custid

(830 row(s) affected)
Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Orders'. Scan count 1, logical reads 21, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Customers'. Scan count 1, logical reads 2, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.


SELECT C.custid, C.companyname,
O.orderid, O.orderdate
FROM Sales.Customers AS C
INNER JOIN Sales.Orders AS O
ON C.custid = O.custid
WHERE O.custid < 5

(30 row(s) affected)
Table 'Customers'. Scan count 0, logical reads 60, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Orders'. Scan count 1, logical reads 21, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

在第二个查询中,我用O.custid < 5来限制行仍然会给我逻辑读取60?对于customer表中的第一个查询,它应该小于21。

1 个答案:

答案 0 :(得分:3)

评论太长了。

您需要查看两个查询的查询计划。 SQL Server有几个用于执行这些查询的选项。例如,以下是一些例子:

  • 使用索引扫描Customers并在Orders中查找每个订单。
  • 扫描Orders表并在Customers
  • 中查找每位客户
  • OrdersCustomers创建哈希表,然后将结果合并到哈希表中。
  • CustomersOrders进行排序并进行合并加入。

(毫无疑问还有其他可能性)。

在任何情况下,SQL优化器都会选择执行join的最佳方法。添加where子句时,最佳解决方案可能会有所不同。这是预期的,并表明优化器正在完成其工作。