" in"中的多个列声明

时间:2014-09-07 06:30:57

标签: sql db2 db2-400

我正在使用DB 2,我正在尝试编写一个查询,该查询针对给定的一组值检查多个列。类似于字段a,字段b和字段c对着值x,y,z,f。我能想到的一种方法是使用或field a in ('x','y','z','f') or field b in .... and so on编写相同的条件3次。如果有其他有效且简单的方法可以让我知道。我正在寻找一个查询,如果任何条件是真的返回是否否。请指教!

4 个答案:

答案 0 :(得分:1)

这可能也可能不适用于as400:

create table a (a int not null, b int not null);
insert into a (a,b) values (1,1),(1,3),(2,3),(0,23);

select a.* 
from a 
where a in (1,2) or b in (1,2);

A           B          
----------- -----------
          1           1
          1           3
          2           3

重写为联接:

select a.* 
from a 
join ( values (1),(2) ) b (x) 
    on b.x in (a.a, a.b); 

A           B          
----------- -----------
          1           1
          1           3
          2           3

答案 1 :(得分:1)

假设列数据类型相同,创建一个子查询,将要用IN搜索的所有列连接到一个带有联合的列

SELECT *
FROM (
        SELECT 
        YOUR_TABLE_PRIMARY_KEY
        ,A AS Col
        FROM YOUR_TABLE
        UNION ALL
        SELECT 
        YOUR_TABLE_PRIMARY_KEY
        ,B AS Col
        FROM YOUR_TABLE
        UNION ALL
        SELECT 
        YOUR_TABLE_PRIMARY_KEY
        ,C AS Col
        FROM YOUR_TABLE
) AS SQ
WHERE
    SQ.Col IN ('x','y','z','f')

确保包含表格键,以便您知道数据所指的行

答案 2 :(得分:0)

您可以创建一个描述字符集的正则表达式,并将其与xquery一起使用

答案 3 :(得分:0)

假设您使用受支持的操作系统版本(在7.1 TR6上测试),这应该可行...

with sel (val) as (values ('x'),('y'),('f')) 
select * from mytbl                          
where flda in (select val from sel)          
   or fldb in (select val from sel)          
   or fldc in (select val from sel)          

扩展上述内容,因为您的OP要求"条件为真返回是否则否#34;

假设您已经获得要检查的行的密钥,那么“是”'或空集足够好? somekey是您要检查的行的关键。

with sel (val) as (values ('x'),('y'),('f')) 
select 'yes' from mytbl                          
where thekey = somekey
   and ( flda in (select val from sel)          
        or fldb in (select val from sel)          
        or fldc in (select val from sel)
       )

当你没有匹配的行时,实际上很难返回一个值。这是一种方式。注意我已切换到1 =是,0 =否..

with sel (val) as (values ('x'),('y'),('f')) 
select 1 from mytbl                          
where thekey = somekey
   and ( flda in (select val from sel)          
        or fldb in (select val from sel)          
        or fldc in (select val from sel)
       )
UNION ALL
select 0               
from sysibm.sysdummy1  
order by 1 desc        
fetch first row only