MySQL knex数学运算

时间:2017-05-29 05:23:38

标签: node.js knex.js

我正在使用带有node.js的knex我想做一个数学查询 (我想为已有的值添加+1)

我想在knex

中执行此操作
UPDATE fares SET fare=fare + 70 

这是我在knex中的查询,我在数据库中得到的只是0

knex('table').update({ fares: 'fares' + 70}).then(function() {});

6 个答案:

答案 0 :(得分:2)

试试这个:

knex('table').update({
  fares: knex.raw('?? + 70', ['fares'])
})

答案 1 :(得分:2)

由于表名是'票价'然后适当的答案应该是:

var number = 70;
knex('fares')
    .update({
        fare: knex.raw(`?? + ${number}`, ['fare'])
    })
    .then((result) => {
        console.log(result);
    });

看?您现在可以将任何值传递给该号码

答案 2 :(得分:2)

您不需要使用.raw(),但它可以正常使用。有内置功能可以使用.increment()进行增量。请参阅:doc link

来自文档的示例:

knex('accounts')
  .where('userid', '=', 1)
  .increment('balance', 10)

...并使用您的表/字段名称和更新金额的值变量。

knex('fares')
  .increment('fare', fareIncrementAmount)

快乐的编码!

答案 3 :(得分:0)

在knex中,它只是作为string plus number运行,将其更改为:

knex('table').update({ fares: '`fares` + 70'}).then(function() {});

答案 4 :(得分:0)

knex('table').select(fares).then(res=>{ //clean the data from res return knex('table').update(fares , res + 70}).then(function() {}); })

答案 5 :(得分:0)

有内置的方法可以实现这一目标,

1。增量

Increment方法将帮助您将列值增加一些特定值,请参考官方文档中的示例

knex('accounts').where('userid', '=', 1).increment('balance', 5)
  

输出:更新accounts设置balance = balance + 5,其中userid = 1

2。减量

knex('accounts').where('userid', '=', 1).decrement('balance', 5)
  

输出:更新accounts设置balance = balance-5,其中userid = 1

但是,我没有找到multiplicationdivision的方法。我们可以通过以下raw query来完成

knex.raw('update accounts set balance = (balance * ? ) where id = ?', [10 , 1]).then(function(resp) { ... });
  

输出:更新帐户设置余额=(余额* 10),其中id = 1;

相同的原始查询也应适用于该部门。

相关问题