[英]Query to find occurrence of at least one value in a set of columns
In the below table, how do I filter out records with at least one 1 and at least one 2 in any of the columns. 在下表中,如何过滤掉任何一列中至少包含1和至少2的记录。 I also only want records for columns with the string 2nd row
in the Name
column. 我还只希望在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
I want the output to be - 我希望输出是-
Col1 Col2 Col3 Col4 Name
1 2 1 2 2nd row
1 2 2nd row
You can use IN
as a shortcut for "col1" = 1 OR ...
. 您可以将IN
用作"col1" = 1 OR ...
的快捷方式。
SELECT *
FROM "elbat"
WHERE 1 IN ("col1",
...,
"col4")
AND 2 IN ("col1",
...,
"col4")
AND "name" = '2nd row';
You can use Postgres' arrays for that: 您可以使用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';
The <@
operator checks, if all elements of the left hand array are included in the right hand array. <@
运算符检查左侧数组的所有元素是否都包含在右侧数组中。 The coalesce() is necessary because you can't put null values into an array. Coalesce()是必需的,因为您不能将空值放入数组中。
Online example: https://rextester.com/CLXWK64603 在线示例: https : //rextester.com/CLXWK64603
If you want you can create an index on the array expression to speed things up. 如果需要,可以在数组表达式上创建索引以加快处理速度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.