繁体   English   中英

从另一个表中为每条记录创建一条记录并将id设置为该字段

[英]Create a record for each record from another table and set the id to the field

我需要写一个迁移。 有一个 profile_details 表和一个帐户表。 我需要在 profile_details 中为帐户表中的每条记录创建一条记录,并将帐户表中的 profile_details_id 字段设置为 profile_details 表中的任何 id。 account record取哪个id并不重要,开头的所有记录都是一样的,最主要的是它们是唯一的。

with profile as (
            INSERT INTO profile_details 
            (id, company_name, country_code, address)
            SELECT uuid_generate_v4(), '', '', ''
            from account    
            returning *
        )
        update account
            Set profile_details_id = profile.id
            FROM profile

由于错误,此选项不起作用

ERROR:  duplicate key value violates unique constraint "UQ_1b48abd3c37e09aac8235b3cd22"
DETAIL:  Key (profile_details_id)=(0ee5ead1-c0f0-4cd3-ae60-a1b493b0d460) already exists.
SQL state: 23505

您只需切换UPDATEINSERT语句:

  • 为每个帐户分配一个随机 UUID,并使用RETURNING获取已创建 UUID 的列表。
  • 使用这些返回的 UUID 在profile_details表中创建新记录。
WITH new_uuids AS (
  UPDATE account
  SET profile_details_id = uuid_generate_v4()
  RETURNING profile_details_id
)

INSERT INTO profile_details(id, company_name, country_code, address)
SELECT
  profile_details_id, '', '', ''
FROM new_uuids

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM