簡體   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