2011-12-05 38 views
-1

我有這種情況: 名爲table 1的表,其列名爲groups。 我該列有一個範圍,我需要拆分並與可變myGroup是否有可能分裂一個SQL單元格,然後比較字符串?

事後比較組目前我這樣做的:

myGroup = 32 
trueGroup = false 

sql = "select * from table1 where groups like '%" & myGroup & "%'" 
set rs = conn.execute(sql) 

if not rs.eof 
    do until rs.eof 
    title = rs("title") 
    groups = rs("groups") 
    groupsSplitted = split(groups, ",") 

    for i = lbound(groupsSplitted) to ubound(groupsSplitted) 
     if cint(myGroup) = cint(groupsSplitted(i)) then 
     trueGroup = true 
     end if 
    next 

    if trueGroup 
     response.write(title) 
    end if 
    next 
end if 

是否有可能做的所有的SQL行? :)

+0

一個設計合理的表格結構可以將這些組分成一個單獨的表格,每個記錄一個組,這樣做完全沒有必要進行這種分割。換句話說:修復你的表格結構,這個問題將消失:http://en.wikipedia.org/wiki/Database_normalization –

回答

4

規範化您的數據。


具有在單個字段(逗號分隔或以其他方式)的多個值是一個壞的反模式。它通過使優化器失去使用索引來破壞性能,並且使得查詢難以編寫和維護。

相反,改變你的架構有一個1:許多關係...

CREATE TABLE map_title_to_group (
    title_id INT, 
    group_id INT, 
    PRIMARY KEY (group_id, title_id) 
) 

然後將查詢簡化...

SELECT title_id FROM map_title_to_group WHERE group_id = ? 

即使如此,你還可以強制約束.. 。
- title_id外鍵的標題表
- group_id外鍵的組表

+0

這將是一個舌頭問題,但現在我真的好奇......有沒有像「壞反模式」那樣的「好反模式」?爲擺脫主題而道歉。 –

+0

@JonP - 好點,我會說沒有「好的反模式」:) [http://en.wikipedia.org/wiki/Anti-pattern] – MatBailie