Postgres - 在从表中选择值时在 INSERT INTO 查询中插入时间戳?

Postgres - Insert timestamps in an INSERT INTO query while selecting values from tables?

我正在尝试 运行 在 Phoenix 应用程序中进行迁移,但是 Postgrex returns 出现以下错误:

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

This 是表的粗略定义。

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
                 )