简单的where子句查询许多列

时间:2013-02-18 10:21:46

标签: sql sql-server

如果可能的话,我想问一下这个问题。

我有一个表格,下面有一些列:

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个不同的列。 有什么方法可以缩短查询时间吗?

2 个答案:

答案 0 :(得分: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 :(得分: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' ))