簡體   English   中英

在使用“with”子句時使用新行的 ID 更新現有記錄

[英]Updating existing records with IDs of new rows while using a “with” clause

平台:Ruby on Rails 與 PostgreSQL 數據庫。

問題:我們正在做一些回填以將我們的數據遷移到新結構。 它造成了一個相當復雜的情況,我們希望盡可能有效地處理它。 部分使用 SQL 解決,類似於:

with rows as (
  insert into responses (prompt_id, answer, received_at, user_id, category_id)
  select prompt_id, null as answer, received_at, user_id, category_id
  from prompts
  where user_status = 0 and skipped is not true
  returning id, category_id
)
insert into category_responses (category_id, response_id)
select category_id, id as response_id
from rows;

表和列已被混淆/簡化,因此其背后的原因可能不那么清楚,但 category_responses 是一個多對多連接表。 我們正在做的是獲取現有提示,並為每個提示創建一組空響應(答案為 NULL)。

缺少的部分是將提示中的記錄與新創建的響應相關聯。 有沒有辦法在查詢中做到這一點? 如果可能的話,我想避免在答案中添加 prompt_id 列,但我猜這將是一種處理方法,包括在returning子句中,然后發出第二個查詢來更新提示表 - 無論如何我甚至不確定是否可以使用單個with子句的結果運行多個查詢。

實現這一目標的最佳方法是什么?

我已決定添加所需的列,並將查詢更新如下:

with tab1 as (
  insert into responses (prompt_id, answer, received_at, user_id, category_id, prompt_id)
  select prompt_id, null as answer, received_at, user_id, category_id
  from prompts
  where user_status = 0 and skipped is not true
  returning id, category_id, prompt_id
),
tab2 as (
  update prompts
  set response_id = tab1.response_id,
  category_id = tab1.category_id
  from tab1
  where prompts.id = tab1.prompt_id
  returning prompts.response_id as response_id, prompts.category_id as category_id
)
insert into category_responses (category_id, response_id)
select category_id, id as response_id
from tab2;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM