postgresql 如何一次向postgres表中插入多个值?

guicsvcw  于 2023-04-29  发布在  PostgreSQL
关注(0)|答案(7)|浏览(218)

我有一个表,我试图一次更新多个值。下面是表模式:

Column     |  Type   | Modifiers 
---------------+---------+-----------
 user_id       | integer | 
 subservice_id | integer |

我有user_id,想一次插入多个subservice_id。在Postgres中是否有一种语法可以让我做这样的事情

insert into user_subservices(user_id, subservice_id) values(1, [1, 2, 3]);

我该怎么做?

2jcobegt

2jcobegt1#

多值插入语法为:

insert into table values (1,1), (1,2), (1,3), (2,1);

但是krokodilko的回答要圆滑得多。

xytpbqjk

xytpbqjk2#

尝试:

INSERT INTO user_subservices(user_id, subservice_id) 
SELECT 1 id, x
FROM    unnest(ARRAY[1,2,3,4,5,6,7,8,22,33]) x

演示:http://www.sqlfiddle.com/#!15/9a006/1

vaj7vani

vaj7vani3#

krokodilko回答的简短版本:

insert into user_subservices(user_id, subservice_id) 
values(1, unnest(array[1, 2, 3]));
lndjwyie

lndjwyie4#

一个稍微相关的答案,因为每次我试图记住这个答案时,我都会发现这个问题。插入多行多列

insert into user_subservices (user_id, subservice_id)
select *
from unnest(array[1, 2], array[3, 4]);
6ie5vjzr

6ie5vjzr5#

更健壮的示例,当您需要为另一个表中的每一行插入多行时:

INSERT INTO user_subservices (user_id, subservice_id)
SELECT users.id AS user_id, subservice_id
FROM users
CROSS JOIN unnest(ARRAY[1,2,3]) subservice_id;
sirbozc5

sirbozc56#

导入值一次但避免重复的好方法如下:

insert into schema.mytable (col1,col2) 
select col1, col2 from schema.mytable 
UNION
values 
('row1-col1','row1-col2'),
('row2-col1','row2-col2'),
('row3-col1','row3-col2')
except
select col1, col2 from schema.mytable;
vuv7lop3

vuv7lop37#

对于多个值,此函数可能会有所帮助。
此函数生成多个值

const _multiInsert = arrOfValues => {
    // removes lastCharacter
    const _remLastChar = str => str.slice(0, str.length - 1);

      let foramttedQuery = '';

      arrOfValues.forEach(row => {
        let newRow = '';
        for (const val of Object.values(row)) {
          let newValue = '';
          if (typeof val === 'string') newValue = `'${val}',`;
          else newValue = `${val},`;
          newRow = newRow.concat(newValue);
        }

        foramttedQuery = foramttedQuery.concat(`(${_remLastChar(newRow)}),`);
      });

      return _remLastChar(foramttedQuery);
    };

    const arr_Of_Values = [
        {
            id: 1,
            name: "SAMPLE_NAME_1",
        },
        {
            id: 2,
            name: "SAMPLE_NAME2",
        }
    ]

    const query_template = `INSERT INTO TABLE_NAME VALUES ${_multiInsert(arr_Of_Values)}`
    
 console.log(query_template)

相关问题