我的查询速度很慢,我想让它更快 - 有可能吗?
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
表中,我在Client
和Product
之间建立了联系。我希望有类似于Client
和Product
记录的笛卡尔积的内容,但我还必须有来自Client
和Product
表的列。
列类型:
- Date
- smalldatetime
,
- Levels
- varchar
,
- Used_id
- int
,
- Z_id
,D_id
,Client_id
,Product_id
- uniqueidentifier
。
答案 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
。