[英]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
您只需切换UPDATE
和INSERT
语句:
RETURNING
获取已创建 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.