如何在Knex中编写mysql子查询?

问题描述 投票:0回答:1

我试图在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'

mysql subquery knex.js koa
1个回答
0
投票

您可以将.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);
    })
© www.soinside.com 2019 - 2024. All rights reserved.