INSERT INTO … FROM SELECT … RETURNING id mappings

前端 未结 3 1689
梦谈多话
梦谈多话 2020-12-16 19:50

I\'m using PostgreSQL 9.3.

I want to duplicate some of the db records. Since I\'m using an auto-increment pk id for the table, I want to get back the id mappings fro

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-16 19:57

    if id column of posts generated by nextval('posts_id_seq'::regclass) you can manually call this function for every new row

    with
    sel as (
      SELECT id, title, nextval('posts_id_seq'::regclass) new_id
      FROM   posts
      WHERE  id IN (1,2)
    ),
    ins as (
      INSERT INTO posts (id, title)
      SELECT new_id, title
      FROM sel
    )
    SELECT id, new_id
    FROM sel
    

    it'l works with any data, include non-unique title

提交回复
热议问题