sql:从jsonb列获取不同的值

时间:2018-08-27 22:40:35

标签: sql postgresql stored-procedures jsonb

我正在尝试从PostgreSQL数据库表中获取不同的sample_id值。除了将它们嵌入在JSONB字段中之外,这将很简单。

这是我运行select * from event limit 10时数据库的外观:

 id | step | event_date | event_status |           payload
----+------+------------+--------------+-----------------------------
  1 |    1 | 2018-01-10 | success      | {"x": "y", "sample_id": [0]}
  2 |    2 | 2018-01-12 | success      | {"x": "y", "sample_id": [0]}
  3 |    3 | 2018-01-14 | success      | {"x": "y", "sample_id": [0]}
  4 |    1 | 2018-01-13 | success      | {"x": "y", "sample_id": [1, 38, 63]}
  5 |    2 | 2018-01-15 | success      | {"x": "y", "sample_id": [1]}
  6 |    3 | 2018-01-17 | pending      | {"x": "y", "sample_id": [1]}
  7 |    1 | 2018-01-16 | success      | {"x": "y", "sample_id": [2]}
  8 |    2 | 2018-01-18 | success      | {"x": "y", "sample_id": [2, 55]}
  9 |    3 | 2018-08-20 | success      | {"x": "y", "sample_id": [2]}
 10 |    1 | 2018-01-19 | success      | {"x": "y", "sample_id": [3]}

对于以下输出,我应该获取以下数据:[0, 1, 2, 3, 38, 55, 63](排序并不重要)。

我已经研究过使用JSONB field functions,但没有运气。知道如何构造这样的查询吗?

1 个答案:

答案 0 :(得分:1)

尝试使用jsonb_array_elements_text

select distinct jsonb_array_elements_text(payload->'sample_id') 
from event

或者,如果您希望将值作为数组而不是记录集,则可以:

select array_agg(distinct e.v) from event 
join lateral jsonb_array_elements_text(payload->'sample_id') e(v)
on true
相关问题