【问题标题】:SQL: How to extract only rows matching condition 'WHERE column1 ILIKE column2' (where column1 is integer and column2 is jsonb)?SQL:如何仅提取匹配条件\'WHERE column1 ILIKE column2\'的行(其中column1是整数,column2是jsonb)?
【发布时间】:2022-11-03 23:08:23
【问题描述】:

我正在使用postgresql。

假设我有这个表名my_table

  id | idcm |  stores |     du     |     au     |              dtc              | 
  ----------------------------------------------------------------------------------
   1 | 20447 | [2, 5] | 2022-11-02 | 2022-11-15 | 2022-11-03 11:12:19.213799+01 | 
   2 | 20456 | [2, 5] | 2022-11-02 | 2022-11-15 | 2022-11-03 11:12:19.213799+01 | 
   3 | 20478 | [2, 5] | 2022-11-02 | 2022-11-15 | 2022-11-03 11:12:19.213799+01 | 
   4 | 20482 | [2, 5] | 2022-11-02 | 2022-11-15 | 2022-11-03 11:12:19.213799+01 | 
   5 | 20485 | [2, 5] | 2022-11-02 | 2022-11-15 | 2022-10-25 20:25:08.949996+02 | 
   6 | 20497 | [2, 5] | 2022-11-02 | 2022-11-15 | 2022-10-25 20:25:08.949996+02 |
   7 | 20499 | [2, 5] | 2022-11-02 | 2022-11-15 | 2022-10-25 20:25:08.949996+02 | 

我只想选择具有id 值的行等于stores(该行)中的数组元素之一。
但是stores的类型不是数组,是jsonb。

所以我想得到这样的东西:

  id | idcm |  stores |     du     |     au     |              dtc              | 
  ----------------------------------------------------------------------------------
   2 | 20456 | [2, 5] | 2022-11-02 | 2022-11-15 | 2022-11-03 11:12:19.213799+01 | 
   5 | 20485 | [7, 5] | 2022-11-02 | 2022-11-15 | 2022-10-25 20:25:08.949996+02 | 
   6 | 20497 | [2, 6] | 2022-11-02 | 2022-11-15 | 2022-10-25 20:25:08.949996+02 |
   7 | 20499 | [5, 7] | 2022-11-02 | 2022-11-15 | 2022-10-25 20:25:08.949996+02 | 

我试过了

select * from my_table where stores::text ilike id::text;

但它返回零行,因为我需要在id 之前和之后放置通配符%
所以我尝试过

select * from my_table where stores::text ilike %id%::text;

但我得到一个语法错误。

【问题讨论】:

  • 对不起,它是id。问题已更新

标签: sql postgresql jsonb


【解决方案1】:

将 ID 转换为单个 JSON 值后,您可以使用 contains operator

select *
from the_table
where stores @> to_jsonb(id)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-20
    • 2019-03-14
    • 2020-06-11
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多