You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将原生SQL转换为Knex查询结果不符,寻求技术帮助

问题描述

需要从数据库中获取满足以下条件的数据:payment_result为'Success',或者payment_type为'bank'且status为2。对应的原生SQL如下:

SELECT users.name, 
    users.company, 
    member_trans.amount, 
FROM transactions
RIGHT JOIN 
users ON transactions.payer_dn = users.displayno 
WHERE 
users.account_number = '123456A'
AND (transactions.payment_result = 'Success' 
OR (transactions.payment_type = 'bank' AND transactions.status = 2))

自行编写的Knex查询未返回预期结果,代码如下:

return this.knex('transactions')
        .select(
            'users.name', 
            'users.company_name', 
            'transactions.amount',    
        )
        .rightJoin('users','transactions.payer_dn', 'users.displayno')
        .where('users.account_number', '123456A')
        .andWhere(function(){
            this.where('transactions.payment_result', 'Success' )
            .orWhere({'transactions.payment_type':'bank','transactions.status': 2})
        })

怀疑问题出在.andWhere()子句中,求解决方法。


问题原因与修正

你的Knex代码里,orWhere的对象写法会直接生成payment_type = 'bank' AND transactions.status = 2,没有用括号将这两个条件包裹成一个整体,虽然逻辑看似和原生SQL一致,但Knex的条件嵌套规则需要显式用子函数来实现括号分组。另外你还写错了一个字段:原生SQL里是users.company,你写的是users.company_name,这会导致字段不存在的错误。

修正后的Knex代码如下,完全匹配原生SQL的逻辑结构:

return this.knex('transactions')
  .select(
    'users.name', 
    'users.company',
    'transactions.amount'
  )
  .rightJoin('users', 'transactions.payer_dn', 'users.displayno')
  .where('users.account_number', '123456A')
  .andWhere(function() {
    this.where('transactions.payment_result', 'Success')
    // 用子函数包裹payment_type和status的AND组合,生成括号
    .orWhere(function() {
      this.where('transactions.payment_type', 'bank')
          .andWhere('transactions.status', 2);
    });
  });

内容的提问来源于stack exchange,提问作者ramedju

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 09:35:14