You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL如何查询包含指定元素的JSONB数组列对应的location_id

你可以用PostgreSQL jsonb类型的内置操作符实现查询,以下是两种常用方案:

方案1:使用?操作符(推荐,性能最优)

?是jsonb类型的原生操作符,可直接判断顶层数组是否包含指定字符串元素,支持GIN索引加速:

SELECT location_id 
FROM Node_Mapping 
WHERE node_ids ? 'uuid101';

如果查询频率较高,建议给node_ids列建GIN索引提升查询效率:

CREATE INDEX idx_node_mapping_node_ids ON Node_Mapping USING GIN (node_ids);

方案2:展开数组后匹配

如果需要更复杂的筛选逻辑,可以把jsonb数组展开成行后过滤:

SELECT DISTINCT nm.location_id
FROM Node_Mapping nm,
     jsonb_array_elements_text(nm.node_ids) AS node_val
WHERE node_val.value = 'uuid101';

补充说明

如果你的node_ids中存储的是UUID类型而非字符串,可使用包含操作符@>实现:

SELECT location_id 
FROM Node_Mapping 
WHERE node_ids @> '"uuid101"'::jsonb;

内容的提问来源于stack exchange,提问作者Akash Beura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 14:06:03