[英]How to store comma-separated values row by row in postgresql
Input:输入:
('{"user":{"status":1,"loginid":1,"userids":{"userid":"5,6"}}}')
I want to insert into my table like this:我想像这样插入到我的表中:
userid loginid status
---------------------------
5 1 1
6 1 1
Use regexp_split_to_table().
使用
regexp_split_to_table().
Assuming that the columns are integers:假设列是整数:
with input_data(data) as (
values
('{"user":{"status":1,"loginid":1,"userids":{"userid":"5,6"}}}'::json)
)
-- insert into my_table(userid, loginid, status)
select
regexp_split_to_table(data->'user'->'userids'->>'userid', ',')::int as userid,
(data->'user'->>'loginid')::int as loginid,
(data->'user'->>'status')::int as status
from input_data
userid | loginid | status
--------+---------+--------
5 | 1 | 1
6 | 1 | 1
(2 rows)
Would be simpler with an array (JSON array) to begin with.使用数组(JSON 数组)开始会更简单。 The you can use
json_array_elements_text(json)
.您可以使用
json_array_elements_text(json)
。 See:看:
Convert the list you have to an array with string_to_array()
.使用
string_to_array()
将您拥有的列表转换为数组。 Then unnest()
.然后
unnest()
。
SELECT unnest(string_to_array(js#>>'{user,userids,userid}', ',')) AS userid
, (js#>>'{user,loginid}')::int AS loginid
, (js#>>'{user,status}')::int AS status
FROM (
SELECT json '{"user":{"status":1,"loginid":1,"userids":{"userid":"5,6"}}}'
) i(js);
I advise Postgres 10 or later for the simple form with unnest()
in the SELECT
list.对于
SELECT
列表中带有unnest()
的简单形式,我建议 Postgres 10 或更高版本。 See:看:
I avoid regexp functions for simple tasks.我避免在简单任务中使用正则表达式函数。 Those are powerful, but substantially more expensive.
这些功能强大,但要贵得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.