[英]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.