[英]How can I improve the performance of this slow query
我有以下查詢,大約需要10分鍾。 我需要這個要快得多。 有什么想法可以調優該查詢嗎? 該r_pos_transaction_head
表有下500000條記錄一點點,而r_pos_transaction_detl
具有下90萬點的記錄一點點。
我創建了我認為合適的索引(您可以在計划中看到它們在使用中)。
truncate table t_retail_history
insert into t_retail_history
select
h.source_db as legacy_source_db,
h.company as legacy_company,
h.store_code as legacy_store_code,
h.register as legacy_register,
cast(h.register as char(1)) + '/' + cast(h.transaction_no as varchar(10)) as legacy_transaction_no,
t_warehouse.store_number as store_number,
h.transaction_no as reference,
convert(varchar(10),dbo.datefromdays(h.date),103) as transaction_date,
convert(varchar(5),dateadd(second,h.time,cast(cast(getdate() as date) as datetime)), 108) as transaction_time,
d.product_code as legacy_product_code,
coalesce(d.colour_no,0) as legacy_colour_no,
coalesce(g_colour_name_replacement.new_colour_name,s.colour_name,'') as legacy_colour_name,
coalesce(d.size_no,0) as legacy_size_no,
coalesce(s.size_code,'') as legacy_size_code,
d.price_inc_tax as legacy_price_inc_tax,
d.sku_no as legacy_sku_no,
null as barcode,
d.quantity as qty,
d.nett_total as sales_total,
null as person_code,
t_warehouse.destination_busdiv_prefix
from
svi.r_pos_transaction_head h
inner join
svi.r_pos_transaction_detl d on
d.company = h.company
and d.store_code = h.store_code
and d.register = h.register
and d.tx_code = h.transaction_no
inner join
svi.g_skus s on
s.company = h.company
and s.product_code = d.product_code
and (
s.colour_position = d.colour_no
or s.colour_position is null and d.colour_no = 0
)
and (
s.size_position = d.size_no
or s.size_position is null and d.size_no = 0
)
left outer join
g_colour_name_replacement on
g_colour_name_replacement.product_code = d.product_code
and g_colour_name_replacement.old_colour_name = s.colour_name
left outer join
t_warehouse on
t_warehouse.legacy_svi_code = right('000' + cast(h.store_code as nvarchar(5)),3)
where
d.quantity <> 0
and d.nett_total <> 0
任何幫助表示贊賞!
就像每個人都建議的那樣,查詢是正確編寫的,請嘗試在連接的字段上添加一些索引。
對我而言,查詢的糟糕之處在於:
and (
s.colour_position = d.colour_no
or s.colour_position is null and d.colour_no = 0
)
and (
s.size_position = d.size_no
or s.size_position is null and d.size_no = 0
)
因為INNER JOIN
語句中的OR condition
是性能殺手 。 他們有很多技巧來避免這種情況(例如,對每個條件進行2次左連接,然后在where子句中刪除發生為null的左連接)。
我只是做了其他一些研究,我發現了有關stackoverflow的這篇文章為您提供了一些建議。 您應該嘗試使用Union選項來不重建所有SELECT字段。
我沒有時間為您重寫所有查詢,請隨時告知我。
您可以使用索引視圖來執行更好的加入。 執行更好的索引編制,因此可以使用索引查找來代替索引掃描。 圖像百分比總和不是100%,其他位置在哪里?
似乎您沒有所需的索引來支持您的查詢。 您應該查看是否可以在聯接的列上創建索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.