gpt4 book ai didi

postgresql - 在 knex 中使用子查询插入默认值

转载 作者:行者123 更新时间:2023-11-29 14:35:40 26 4
gpt4 key购买 nike

我有这个问题;

knex('metrics').insert(function() {
this.select('metric as name')
.from('stage.metrics as s')
.whereNotExists(function() {
this.select('*')
.from('metrics')
.where('metrics.name', knex.raw('s.metric'))
})
})

metrics 表有两列;一个递增的 ID 和名称。我希望这会插入到名称列中,因为子查询只有一列、标签名称和默认 ID。然而,相反,它提示说我提供了一个类型为 character varying for my integer column id 的列。如何明确表示我希望 id 取默认值?

最佳答案

这个可以解决问题

knex('metrics').insert(function() {
this
.select([
knex.raw('null::bigint as id'), // or any other type you need (to force using default value you need to pass explicitly null value to insert query)
'metric as name'
])
.from('stage.metrics as s')
.whereNotExists(function() {
this.select('*')
.from('metrics')
.where('metrics.name', knex.raw('s.metric'))
})
})

我知道,看起来有点hacky。很高兴在 knex API 中看到类似的东西(下面的示例是一个提案,而不是一个工作示例)

knex('table_name')
.insert(
['name', 'surname'],
function () {
this.select(['name', 'surname']).from('other_table'))
}
)

产生

insert into table_name (name, surname) select name, surname from other_table;

我不确定这个界面,但你明白了。就像显式写入要插入的字段一样。

关于postgresql - 在 knex 中使用子查询插入默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45089171/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com