[英]Create a record for each record from another table and set the id to the field
I need to write a migration.我需要写一个迁移。 There is a profile_details table and an account table.有一个 profile_details 表和一个帐户表。 I need to create an record in profile_details for each record in the account table and set the profile_details_id field from the account table to any id from the profile_details table.我需要在 profile_details 中为帐户表中的每条记录创建一条记录,并将帐户表中的 profile_details_id 字段设置为 profile_details 表中的任何 id。 It doesn't matter which id the account record will get, all records at the beginning will be the same, the main thing is that they are unique. 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
This option does not work due to an error由于错误,此选项不起作用
ERROR: duplicate key value violates unique constraint "UQ_1b48abd3c37e09aac8235b3cd22"
DETAIL: Key (profile_details_id)=(0ee5ead1-c0f0-4cd3-ae60-a1b493b0d460) already exists.
SQL state: 23505
You just have to switch your UPDATE
and INSERT
statements:您只需切换UPDATE
和INSERT
语句:
RETURNING
to get a list of the created UUIDs.为每个帐户分配一个随机 UUID,并使用RETURNING
获取已创建 UUID 的列表。profile_details
table.使用这些返回的 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.