SQL字段拆分優化。本站提示廣大學習愛好者:(SQL字段拆分優化)文章只能為提供參考,不一定能成為您想要的結果。以下是SQL字段拆分優化正文
明天看到一條用函數處置銜接的SQL,是群裡某位網友的,SQL語句以下:
SELECT SO_Order.fdate , SO_Order.fsn FROM so_order INNER JOIN so_orderitem ON CHARINDEX(so_Orderitem.fid, SO_Order.fid) >= 1 WHERE so_order.FOrderDate = '2015-09-06'
語句不算龐雜,只是履行比擬慢,上面是關於這SQL語句的一些信息:
--1.SQL履行203條數據
--2.耗時12秒
--3.so_order表的fid字段是字符串聚集,
--由1-2個字符串構成,用','分隔
SELECT COUNT(*) FROM SO_Order WHERE so_order.FOrderDate = '2015-09-06'--24 SELECT COUNT(*) FROM so_Orderitem--414154
經由過程剖析履行籌劃,so_order和so_orderitem走嵌套輪回是准確的,查詢的瓶頸是在so_orderitem的索引
掃描上。是以,我們要經由過程改寫SQL,到達so_orderitem走索引查找的目標。
將so_order表的fid字段拆分紅2個字段,然後union all成一個成果集,再和so_orderitem聯系關系,便可讓so_orderitem表走索引查找。
改寫的SQL以下:
;WITH x0 AS ( SELECT fdate , fsn , LEFT(fid, CASE WHEN CHARINDEX(',', fid, 1) = 0 THEN 0 ELSE CHARINDEX(',', fid, 1) - 1 END) AS fid FROM so_order WHERE FOrderDate = '2015-09-06' UNION ALL SELECT fdate , fsn , RIGHT(fid, LEN(fid) - CHARINDEX(',', fid, 1)) AS fid FROM so_order WHERE FOrderDate = '2015-09-06' ) SELECT SO_Order.fdate , SO_Order.fsn FROM x0 so_order INNER JOIN so_orderitem ON so_Orderitem.fid = SO_Order.fid
上面是SQL改寫後,網友的反應截圖
改寫後SQL的履行籌劃以下: