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

标签 sql postgresql ecto

我正在尝试在 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

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
                 )

关于sql - Postgres - 在从表中选择值时在 INSERT INTO 查询中插入时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56059308/

相关文章:

sql - 在 Oracle 中创建 CTE

mysql - SQL 报告每个供应商、每种木材类型和等级

ruby-on-rails-3 - Rails 3 Heroku 上的 postgreSQL 查询问题 - bool 值与复选框参数 = 'on'

arrays - WHERE条件在循环中使用数组中的信息

postgresql - 如何使用 Ecto/Phoenix 从数据库中选择最新条目

sql - Go 中的 Postgres 列表参数(使用 database/sql 和 pq)

sql - 如何获取 Sqlite3 数据库中的列名列表?

sql - 如何在查询结果上运行函数?

elixir - 如何使用 join 编写 ecto 查询

elixir - 带有条件的 Ecto 关联