简体   繁体   English

如何在postgresql中逐行存储逗号分隔值

[英]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);

db<>fiddle here db<> 在这里摆弄

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.

相关问题 如何在 Oracle 中将多行值转换为具有逗号分隔值不同 ID 的一行 - How to convert Multiple row values to one row with comma-separated value different ID in Oracle 带有 Group By 子句的 SQL 逗号分隔行 - SQL comma-separated row with Group By clause SQL查询或过程,每个不同的行具有不同的值和逗号分隔的值 - SQL query or procedure with distinct and comma-separated values for each distinct row 根据行中存在的逗号分隔ID获取数据 - SQL - Get data on the basis of comma-separated ids present in row - SQL 如果一列包含逗号分隔的值,请分别制作单独的一行 - Make a separate row respectively if a column contains comma-separated value 在MySql中将结果行从查询转换为逗号分隔的字符串 - In MySql convert resulted row from query to comma-separated string 如果列包含逗号分隔值,请创建单独的行 - Make a separate row if a column contains comma-separated value 拆分逗号分隔的输入框值,然后存储在数据库中 - Split comma-separated input box values and then store in database 查询逗号分隔的id到逗号分隔值 - Query for comma-separated ids to comma-separated values 如何在Oracle表中将逗号分隔的值拆分为多行 - How to split comma-separated values into multiple rows in Oracle table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM