如何使用 knex.js 以另一列作为条件编写 CASE 子句

How to write a CASE clause with another column as a condition using knex.js

所以我的代码如下所示:

.select('id','units',knex.raw('case when units > 0 then cost else 0 end'))

但它给我这样的错误

hint: "No operator matches the given name and argument type(s). You might need to add explicit type casts."

知道我应该如何纠正我的代码以便我可以使用另一列作为不同于列的条件吗?

我没有遇到与您相同的错误:

CASE types integer and character varying cannot be matched

但无论如何,问题是您要比较苹果和橙子。 Postgres 对列类型非常严格,因此尝试将整数 0 和字符串(cost 的值)放在同一列中不会导致隐式转换。

把你的输出变成一个字符串就可以了:

  .select(
    "id",
    "units",
    db.raw("CASE WHEN units > 0 THEN cost ELSE '0' END AS cost")
  )

示例输出:

[
  { id: 1, units: null, cost: '0' },
  { id: 2, units: 1.2, cost: '2.99' },
  { id: 3, units: 0.9, cost: '4.50' },
  { id: 4, units: 5, cost: '1.23' },
  { id: 5, units: 0, cost: '0' }
]