SQL left join- 变慢 table?

SQL left join- slowing on smaller table?

使用 SQL 服务器快递。我有一个销售交易主控 table,它保留所有销售交易数据的历史记录。此 table 每天更新以添加一个新行来捕获对销售交易的任何更改。

根据这个 table,我创建了两个视图 - 一个用于 Sales_Closed,一个用于 Open_Bookings。每个视图 returns 完全相同的列集,只是分别过滤了数据。

当我从每个 select * 时,会发生以下情况:

另外 - 我创建了一个 table 来捕获我最终输出所需的所有相关数据组合,该报告显示 1 年前和 1 年前的未结订单和已结束销售。此 table 中标题为 Work_Template_month 的列是:UPC、位置、渠道、销售类型、月、年和财政年度。

运行 Select * 从此 table returns:

那么有趣的是:如果我 运行 这个 SQL 在这里查询,然后交换(第 14 行)

LEFT OUTER JOIN dbo.bookings_open AS E  

LEFT OUTER JOIN dbo.sales_closed AS E

Sales_Closed 运行23 秒后

Bookings_open 运行 秒 3:00!!!!

为什么较小的 table 需要 8 倍的时间?!

SELECT       
    D.upc, 
    D.sales_type, 
    D.channel, 
    D.month, D.year, D.fiscal_year,
    D.adj_location,
    SUM(E.qty_sold) AS Sales_Qty, 
    SUM(CAST(E.total_adjust_dollars AS money)) AS Sales_Dollars
FROM            
    dbo.work_template_month AS D 
LEFT OUTER JOIN 
    dbo.bookings_open AS E ON D.upc = E.upc 
                           AND D.sales_type = E.sales_type 
                           AND D.channel = E.channel_name 
                           AND D.month = E.shipped_month 
                           AND D.year = E.shipped_year 
                           AND D.adj_location = E.adj_location
GROUP BY 
    D.upc, D.sales_type, D.channel, 
    D.month, D.year, D.fiscal_year,
    D.adj_location

执行计划: Open_Bookings: open_bookings_execution_plan

Sales_Closed: sales_closed_execution_plan

您的加入条件有问题

ON D.upc = E.upc 
                           AND D.sales_type = E.sales_type 
                           AND D.channel = E.channel_name 
                           AND D.month = E.shipped_month 
                           AND D.year = E.shipped_year 
                           AND D.adj_location = E.adj_location

如果连接是在外键的主键上进行的,那么您在多个字段上查询会更好,这就是执行程序在其中进行散列查找的原因。 尝试向 sales_type、Channel_month_year 和 adj_location

添加覆盖索引

我最终使用 Open_Bookings 的视图创建了 table(具有确切的列),现在称为 Open_bookings_tbl

我将第 14 行替换为: LEFT OUTER JOIN dbo.bookings_open_tbl AS E

这现在运行了 19 秒,我仍然感到困惑,高兴但困惑。下面的执行计划。

Bookings_table_Execution_Plan