我试图在knex中编写mysql子查询sql,但查询结果是不受欢迎的。
这是我的MySQL查询:
select *
from istifta
where istifta_id not in (
select istifta_id
from status
where status = 'divided'
)
这是我的查询转换为Knex:
subquery = await ctx.knex
.select('istifta_id')
.from('status')
.where('status', 'divided')
result = await ctx.knex
.select()
.from('istifta')
.where('istifta_id', 'not in', subquery)
MySQL查询返回两行,所有这些行都没有status = 'divided'
而Knex返回三行,其中一行有status = 'divided'
您可以将.whereNotIn
与function()定义选项一起使用来嵌套子查询。您的子查询位于函数()内部:
select('istifta_id').from('status').where('status', 'divided')
和.on
函数只是使调试更容易一点。
result = await ctx.knex.from('istifta')
.whereNotIn( 'istifta_id', function() {
this.select('istifta_id').from('status').where('status', 'divided')
})
.on('query', function(data) {
console.log("TEST001 data:", data); })
.on('query-error', function(ex, obj) {
console.error("TEST002 KNEX query-error ex:", ex, "obj:", obj);
})