![](/img/trans.png)
[英]INSERT rows into multiple tables in a single query, selecting from an involved table
[英]Postgres - Insert timestamps in an INSERT INTO query while selecting values from tables?
我正在嘗試在Phoenix應用程序中運行遷移,但是Postgrex返回以下錯誤:
null value in column "inserted_at" violates not-null constraint
生成該錯誤的查詢是:
execute "INSERT INTO contract_groups
(SELECT c.id, fg.group_id FROM contracts c, folder_groups fg
WHERE c.folder_id = fg.folder_id)"
我嘗試將查詢更新為此:
execute "INSERT INTO contract_groups
(contract_id, group_id, inserted_at)
VALUES ((SELECT c.id, fg.group_id FROM contracts c, folder_groups fg
WHERE c.folder_id = fg.folder_id), NOW())"
但是我又收到一個錯誤,說subquery must return only one column
。
這是表格的粗略定義。
insert into contract_groups (contract_id, group_id, inserted_at)
select c.id, fg.group_id, CURRENT_TIMESTAMP
from contracts c
inner join folder_groups fg
on fg.folder_id = c.folder_id
請注意,這依賴於與語句中的列順序匹配的所選列
更新:
根據評論,嘗試:
insert into contract_groups (contract_id, group_id, inserted_at)
select distinct c.id, -- distinct added to prevent duplicates
fg.group_id,
CURRENT_TIMESTAMP
from contracts c
inner join folder_groups fg
on fg.folder_id = c.folder_id
where not exists ( -- exclude any combos that are in the target table
select 1
from contract_groups cg
where cg.contract_id = c.id
and fg.froup_id = cg.group_id
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.