2013-02-18 46 views
0

我想詢問一下這個查詢是否可能簡單。簡單的where子句查詢很多列

我有一些列的表像下面:

class_01|class_02|class_03|class_04|class_05|class_06|class_07|class_08|class_09| 
Sonto | Botak | Semut | Setting|'<none>'|'<none>'|'<none>'|'<none>'|'<none>'| 

然後我寫一個where子句是這樣的:

SELECT bedrnr 
FROM bedryf 
WHERE class_01 IN ('Sonto', 'Botak', 'Semut', 'Setting') 
    OR class_02 IN ('Sonto', 'Botak', 'Semut', 'Setting') 
    OR class_03 IN ('Sonto', 'Botak', 'Semut', 'Setting') 
    OR class_04 IN ('Sonto', 'Botak', 'Semut', 'Setting') 
    OR class_05 IN ('Sonto', 'Botak', 'Semut', 'Setting') 
    OR class_06 IN ('Sonto', 'Botak', 'Semut', 'Setting') 
    OR class_07 IN ('Sonto', 'Botak', 'Semut', 'Setting') 
    OR class_08 IN ('Sonto', 'Botak', 'Semut', 'Setting') 
    OR class_09 IN ('Sonto', 'Botak', 'Semut', 'Setting') 

這是一個WHERE子句,其中IN的值是相同的有,但它只是想找到9個不同的列。 它使查詢更短的任何方式?

+6

這是一個跡象,表明該模式沒有很好designed.There應該是包含'class'值的單個列,每個可應用的類有一行(必要時還有一個限制行數爲10的約束),如果還有更多的列,可能作爲單獨的表格所示。 – 2013-02-18 10:26:24

+0

你可以在你的9個專欄中使用「Sonto」,「Botak」,「Semut」,「Setting」,「」以外的東西嗎? 「」是什麼意思?它是空字符串還是null或''? – Kaf 2013-02-18 10:59:00

+0

是創建數據庫時的默認值。它的意思是沒有任何數據,並且在編寫查詢時將被C#邏輯清除。 – 2013-02-18 11:03:42

回答

1
select distinct bedrnr 
FROM bedryf unpivot (value for class in (class_01, class_02, class_03, class_04, class_05, class_06, class_07, class_08, class_09)) b 
inner join (
    values ('Sonto'), ('Botak'), ('Semut'), ('Setting') 
) t(thing) on b.value = t.thing 

的SQL Server 2005:

select distinct bedrnr 
FROM bedryf unpivot (value for class in (class_01, class_02, class_03, class_04, class_05, class_06, class_07, class_08, class_09)) b 
inner join (
    select 'Sonto' as thing 
    union all 
    select 'Botak' as thing 
    union all 
    select 'Semut' as thing 
    union all 
    select 'Setting' as thing 
) t(thing) on b.value = t.thing 
1

您應該解決您的架構,但另一種方式(2008+語法)

SELECT bedrnr 
FROM bedryf 
WHERE EXISTS (SELECT class 
       FROM (VALUES(class_01), 
          (class_02), 
          (class_03), 
          (class_04), 
          (class_05), 
          (class_06), 
          (class_07), 
          (class_08), 
          (class_09)) V(class) 
       WHERE class IN ('Sonto', 'Botak', 'Semut', 'Setting'))