首页 > 解决方案 > 为 where 子句中传递的每条记录获取 1 0r 0

问题描述

我有一个带有 jsonb 列数据类型的表

+-----+--------------------------------------------------------------------------------+
| id  |             value                                                              |
+-----+--------------------------------------------------------------------------------+
| 1   | {"t1": "val", "value": [{"id": "1", "name": "abc"},{"id": "2", "name": "xyz"}] |
| 2   | {"t1": "val", "value": [{"id": "2", "name": "xyz"},{"id": "3", "name": "pqr"}] |
+-----+--------------------------------------------------------------------------------*
SELECT 'True' as status 
FROM   table t
where t.value->'value'->-1 -> 'id' IN ('"2"','"1"')

我想获取 Ture 或 false 以及 where 子句中检查的每个 id。

请在此查询中帮助我

标签: postgresql

解决方案


您需要将条件移动到 SELECT 列表中,但您必须遍历所有数组元素:

select t.id, 
       exists(select * 
              from jsonb_array_elements(t.value -> 'value') as v(item) 
              where item ->> 'id' in ('1','2')) as status
from the_table t;

使用 Postgres 12 或更高版本,您可以将所有 ID 提取到一个数组中,然后使用?|运算符:

select t.id, 
       jsonb_path_query_array(t.value -> 'value', '$[*].id') ?| array['1','2'] as status
from the_table t;

推荐阅读