使用左外连接和联合优化SQL查询

时间:2015-07-23 12:43:31

标签: sql sql-server tsql left-join union

我的查询速度很慢,我想让它更快 - 有可能吗?

SELECT 
    k.Date,
    Levels,
    Used_id,
    Z_id,
    D_id,
    k.Client_id,
    f.Product_id
FROM 
    (SELECT Date, Levels, Used_id, Z_id, D_id, Client_id 
     FROM Client_Data
     GROUP BY Date, Levels, Used_id, Z_id, D_id, Client_id) k
LEFT OUTER JOIN 
    (SELECT Date, Client, Product 
     FROM Client_and_Product_Data 
     GROUP BY Date, Client_id, Product) f on f.Date = k.Date and f.Client = k.Client_id
union
SELECT 
    p.Date,
    Levels,
    Used_id,
    Z_id,
    D_id,
    f.Client_id,
    p.Product_id
FROM 
    (SELECT Date, Levels, Used_id, Z_id, D_id, Product_id 
     FROM Product_Data
     GROUP BY Date, Levels, Used_id, Z_id, D_id, Product_id) p
LEFT outer join 
    (SELECT Date, Client, Product 
     FROM Client_and_Product_Data 
     GROUP BY Date, Client, Product) f on f.Date = p.Date and f.Product = p.Product_id;

Client_data表中有9mln记录,Product_data表中有300k记录,Client_and_Product_Data表中有250k记录。

整个查询需要3-4分钟。

我在此查询中执行的操作:在Client_and_Product_Data表中,我在ClientProduct之间建立了联系。我希望有类似于ClientProduct记录的笛卡尔积的内容,但我还必须有来自ClientProduct表的列。

列类型:
- Date - smalldatetime
- Levels - varchar
- Used_id - int
- Z_idD_idClient_idProduct_id - uniqueidentifier

1 个答案:

答案 0 :(得分:1)

您的查询可能会利用索引。我建议:

  • Client_Data(Date, Levels, Used_id, Z_id, D_id, Client_id)
  • Client_and_Product_Data(Date, Client, Product)
  • Product_Data(Date, Levels, Used_id, Z_id, D_id, Product_id)

如果您不需要消除重复项,请删除子查询中的GROUP BY。如果两个查询之间没有重复项,请将UNION更改为UNION ALL