0

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

我有一个表,其中包含如下所示的列:

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 个不同的列中找到。有什么办法可以让查询更短吗?

4

2 回答 2

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' )) 
于 2013-02-18T11:06:11.823 回答
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
于 2013-02-18T11:02:01.627 回答