postgresql - 为 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。
请在此查询中帮助我
解决方案
您需要将条件移动到 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;
推荐阅读
- cmake - cmake 和可移植的 nul //dev/null 设备
- node.js - 基本身份验证 - 未为某些请求添加授权标头
- python - 谁想成为百万富翁 pygame - 50:50 小丑
- ruby - Ruby spawn process, capturing STDOUT/STDERR, while behaving as if it were spawned regularly
- apache-kafka - Kafka 主题是否与 zookeeper 相关联,如果 zookeeper 改变,主题会消失
- typescript - 如何为 create-react-app --typescript 禁用 eqeqeq
- php - 如何在 WooCommerce 结帐页面上显示自定义产品字段?
- vba - ms-project vba 中的文档导出失败
- css - 如何在反应中使网格移动响应
- python - Tensorflow:如何将张量与特定索引连接起来