先說明一下我的需求
我有一個陣列裡面存了所有要查詢的SID
然後我想在SQL中查詢包含那陣列所有值資料列
目前的SQL語法是這樣寫
SELECT DIP IP,
SID Sclass,
DVALUE Note,
FORMAT ([DISTIME], 'yyyy-MM-dd HH:mm:ss') as 斷線時間
FROM tb_connectlog
WHERE CONTIME IS NULL AND
LTRIM(RTRIM(SID)) IN ('WLS077','KPS061','AFR018','AFR019','DTS106','WLS078')
ORDER BY DISTIME DESC
在IN後面的條件如果只有一兩個的時候
查詢速度非常快
但當條件一多的時候
查詢時間就會瞬間變超久
想請問各位大大有什麼建議可以改善這個問題嗎
若參考這篇裡有關 OR 的改善方法
改寫如下試試看
SELECT DIP IP, SID Sclass, DVALUE Note, FORMAT ([DISTIME], 'yyyy-MM-dd HH:mm:ss') as 斷線時間
FROM tb_connectlog
WHERE CONTIME IS NULL AND SID = 'WLS077'
UNION
SELECT DIP IP, SID Sclass, DVALUE Note, FORMAT ([DISTIME], 'yyyy-MM-dd HH:mm:ss') as 斷線時間
FROM tb_connectlog
WHERE CONTIME IS NULL AND SID = 'KPS061'
UNION
SELECT DIP IP, SID Sclass, DVALUE Note, FORMAT ([DISTIME], 'yyyy-MM-dd HH:mm:ss') as 斷線時間
FROM tb_connectlog
WHERE CONTIME IS NULL AND SID = 'AFR018'
UNION
SELECT DIP IP, SID Sclass, DVALUE Note, FORMAT ([DISTIME], 'yyyy-MM-dd HH:mm:ss') as 斷線時間
FROM tb_connectlog
WHERE CONTIME IS NULL AND SID = 'AFR019'
UNION
SELECT DIP IP, SID Sclass, DVALUE Note, FORMAT ([DISTIME], 'yyyy-MM-dd HH:mm:ss') as 斷線時間
FROM tb_connectlog
WHERE CONTIME IS NULL AND SID = 'DTS106'
UNION
SELECT DIP IP, SID Sclass, DVALUE Note, FORMAT ([DISTIME], 'yyyy-MM-dd HH:mm:ss') as 斷線時間
FROM tb_connectlog
WHERE CONTIME IS NULL AND SID = 'WLS078'
另外先做兩件事
1.UPDATE tb_connectlog SET SID=LTRIM(RTRIM(SID))
(SQL 裡就不必每次呼叫)
2.SID 欄位要建索引
謝謝海綿寶寶大大,建完索引好像情況就有稍微改善了
拆兩段試試@@...
declare @Tmp table(
[SID] nvarchar(50),
[DIP IP] nvarchar(50),
[SID Sclass] nvarchar(50),
[DVALUE Note] nvarchar(max),
[DISTIME] datetime
)
insert into @Tmp
select [SID],
[DIP IP],
[SID Sclass],
[DVALUE Note],
[DISTIME]
FROM tb_connectlog
WHERE CONTIME IS NULL
SELECT [DIP IP],
[SID Sclass],
[DVALUE Note],
FORMAT ([DISTIME], 'yyyy-MM-dd HH:mm:ss') as 斷線時間
from @Tmp
where LTRIM(RTRIM(SID)) IN ('WLS077','KPS061','AFR018','AFR019','DTS106','WLS078')
ORDER BY DISTIME DESC
感謝純真的人大大,我等一下來試試看這個方法
提供我的解法當作參考,我會把陣列拆開來當作表格join就好
declare @sids varchar('WLS077,KPS061,AFR018,AFR019,DTS106,WLS078')
SELECT DIP IP,
[SID] as Sclass,
DVALUE Note,
FORMAT ([DISTIME], 'yyyy-MM-dd HH:mm:ss') as 斷線時間
FROM tb_connectlog
inner join string_split(@sids, ',') F on F.[value] = LTRIM(RTRIM(SID))
WHERE CONTIME IS NULL
ORDER BY DISTIME DESC