0

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

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

我正在执行此查询 3 次,同时仅更改 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)?

4

1 回答 1

0

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

如果我正确理解你想要的东西(更新),这样它应该会更快:

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
于 2013-06-22T21:45:15.723 回答