汇总查询的奇怪执行时间

时间:2013-06-22 20:25:46

标签: stored-procedures sql-server-2012

我在这里给出了我正在执行的部分查询:

SELECT SUM(ParentTable.Field1),
       (SELECT SUM(ChildrenTable.Field1)
       FROM ChildrenRable INNER JOIN
           GrandChildrenTable ON ChildrenTable.Id = GrandChildrenTable.ChildrenTableId INNER JOIN
           AnotherTable ON GrandChildrenTable.AnotherTableId = AnotherTable.Id
       WHERE ChildrenTable.ParentBaleId = ParentTable.Id
       AND AnotherTable.Type=1),
       ----
FROM ParentTable
WHERE some_conditions

关系:

ParentTable -> ChildrenTable = 1-to-many
ChildrenTable -> GrandChildrenTable = 1-to-many
GrandChildrenTable -> AnotherTable = 1-to-1

我正在执行此查询三次,同时仅更改Type条件,结果如下:

返回的记录数:

Condition   Total execution time (ms)
Type = 1 :            973
Type = 2 :          78810
Type = 3 :         648318

如果我只执行内连接查询,这里是连接记录的计数:

SELECT p.Type, COUNT(*)
FROM CycleActivities ca INNER JOIN
     CycleActivityProducts cap ON ca.Id = CAP.CycleActivityId INNER JOIN
 Products p ON cap.ProductId = p.Id
GROUP BY p.Type

Type 
---- -----------
1     55152
2     13401
4    102730

那么,为什么使用Type = 1条件的查询比Type = 2的查询执行得快得多,尽管它查询的结果集大4倍(Type is tinyint)?

1 个答案:

答案 0 :(得分:0)

编写查询的方式指示SQL Server为输出的每一行执行JOIN的子查询。

如果我理解你想要的东西(更新),这种方式应该更快:

with cte_parent as (
   select 
      Id,
      SUM (ParentTable.Field1) as Parent_Sum
from ParentTable
group by Id
), 

cte_child as (
    SELECT
       Id,
       SUM (ChildrenTable.Field1) as as Child_Sum
    FROM ChildrenRable 
       INNER JOIN
           GrandChildrenTable ON ChildrenTable.Id = GrandChildrenTable.ChildrenTableId 
       INNER JOIN
           AnotherTable ON GrandChildrenTable.AnotherTableId = AnotherTable.Id
    WHERE 
           AnotherTable.Type=1
       AND
           some_conditions
    GROUP BY Id
)

select cte_parent.id, Parent_Sum, Child_Sum
from parent_cte 
join child_cte on parent_cte.id = child_cte.id