繁体   English   中英

查询以查找一组列中至少一个值的出现

[英]Query to find occurrence of at least one value in a set of columns

在下表中,如何过滤掉任何一列中至少包含1和至少2的记录。 我还只希望在Name列中记录字符串2nd row的列。

Col1 Col2 Col3 Col4 Name
1    1    1    1    1st row
1    2    1    2    2nd row
2    1    1    1    3rd row
1    2              2nd row

我希望输出是-

Col1 Col2 Col3 Col4 Name 
1    2    1    2    2nd row
1    2              2nd row

您可以将IN用作"col1" = 1 OR ...的快捷方式。

SELECT *
       FROM "elbat"
       WHERE 1 IN ("col1",
                   ...,
                   "col4")
             AND 2 IN ("col1",
                       ...,
                       "col4")
             AND "name" = '2nd row';

您可以使用Postgres的数组:

select *
from the_table
where array[1,2] <@ array[coalesce(col1, -1), coalesce(col2, -1), coalesce(col3, -1), coalesce(col4, -1)] 
  and name = '2nd row';

<@运算符检查左侧数组的所有元素是否都包含在右侧数组中。 Coalesce()是必需的,因为您不能将空值放入数组中。

在线示例: https//rextester.com/CLXWK64603

如果需要,可以在数组表达式上创建索引以加快处理速度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM