今天看到一條用函數處理連接的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的執行計劃如下: