[英]Determining order of elements inside json_array - SQL
I have a table kind of like this, let's call it base_table: 我有一个像这样的表,我们称之为base_table:
id | date | json_array
---+-------------+------------------
1 2018-01-01 [{..a..},{..b..}]
2 2018-01-01 [{..c..}]
3 2018-01-01 [{..d..}]
4 2018-01-01 [{..e..},{..f..}]
. . .
. . .
. . .
The json_array column always has either 1 or 2 elements. json_array列始终具有1或2个元素。
I need to make a select in SQL where on each line I can show: the respective id from base_table; 我需要在SQL中进行选择,我可以在每行显示:base_table中的相应id; its order (if the element comes 1st or 2nd inside the array);
它的顺序(如果元素在数组中位于第1或第2位); the element of the json_array.
json_array的元素。
The output should be something like this: 输出应该是这样的:
id | order | json_object
---+-------+------------
1 1 {..a..}
1 2 {..b..}
2 1 {..c..}
3 1 {..d..}
4 1 {..e..}
4 2 {..f..}
. . .
. . .
. . .
But I'm having a lot of trouble with showing the order of the elements... Can anyone help? 但是我在显示元素的顺序方面遇到了很多麻烦......任何人都可以帮忙吗?
The database is in PostgreSQL 9.6.1 该数据库位于PostgreSQL 9.6.1中
Use json_array_elements(json_array) with ordinality
: 将
json_array_elements(json_array) with ordinality
:
with my_table(id, json_array) as (
values
(1, '[{"a": 1}, {"b": 2}]'::json),
(2, '[{"c": 3}]'),
(3, '[{"d": 4}]'),
(4, '[{"e": 5}, {"f": 6}]')
)
select id, ordinality, value
from my_table
cross join json_array_elements(json_array) with ordinality;
id | ordinality | value
----+------------+----------
1 | 1 | {"a": 1}
1 | 2 | {"b": 2}
2 | 1 | {"c": 3}
3 | 1 | {"d": 4}
4 | 1 | {"e": 5}
4 | 2 | {"f": 6}
(6 rows)
Read 7.2.1.4. 阅读7.2.1.4。 Table Functions in the documentation.
表 文档中的 表函数 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.