我需要编写一个迁移。有一个profile_details表和一个account表。我需要在profile_details中为account表中的每个记录创建一个记录,并将account表的profile_dedetails_id字段设置为profile_deletes表中的任何id。账户记录将获得哪个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
语句:
- 为每个帐户分配一个随机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