簡體   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