性能問題可能是遊標(用於while循環)和用戶定義的函數的組合。
如果這些字符串之一是恆定的(如項目關鍵詞),您可以搜索每一個獨立的爲:
select *
from users u
where charindex(';'+<item1>+';', ';'+u.keywords) > 0
union all
select *
from users u
where charindex(';'+<item2>+';', ';'+u.keywords) > 0 union all
另外,一組爲基礎的方法可以工作,但你必須標準化數據(在這裏插入數據以正確格式開始)。也就是說,你想有一個表:
userid
keyword
,另一個具有
itemid
keyword
(如果有不同類型的項目,否則這只是一個關鍵字列表。)
然後您的查詢將如下所示:
select *
from userkeyword uk join
itemkeyword ik
on uk.keyword = ik.keyword
而SQL引擎會執行它的魔法。
現在,你如何創建這樣一個列表?如果只有每個用戶的關鍵詞了一把,那麼你可以這樣做:
with keyword1 as (select u.*, charindex(';', keywords) as pos1,
left(keywords, charindex(';', keywords)-1) as keyword1
from user u
where charindex(';', keywords) > 0
),
keyword2 as (select u.*, charindex(';', keywords, pos1+1) as pos2,
left(keywords, charindex(';', keywords)-1, pos1+1) as keyword2
from user u
where charindex(';', keywords, pos1+2) > 0
),
...
select userid, keyword1
from keyword1
union all
select userid, keyword2
from keyword2
...
要獲得元素在itemKeyWords的最大數量,你可以使用下面的查詢:
select max(len(Keywords) - len(replace(Keywords, ';', '')))
from user
這是你需要一直運行的東西,還是一次性的努力? – dasblinkenlight
我正在運行一些模擬數據挖掘,所以需要做到這一點,只要我的模型改變或如果我想試驗新的公式。可能不是很頻繁 – randomThought