【问题标题】:Only increment the lowest entry in postgres DB using Knex仅使用 Knex 增加 postgres DB 中的最低条目
【发布时间】:2017-05-27 17:54:51
【问题描述】:

我正在尝试获取特定用户的最低记录列的行,然后只增加一列,然后返回它。这是我在下面写的,我认为它会起作用,但它会增加该用户选项的每个计数列。再说一次,我只想要最低的列...

knex('options').where('user_id', user_id)
                        .orderBy('tally', 'asc')
                        .limit(1)
                        .first()
                        .increment('tally', 1)
                        .then((option) => {
                           console.log(option);
                           res.sendStatus(200)
})

【问题讨论】:

  • 您可以使用.toSQL() 检查构建器生成的 SQL 类型。例如,您的查询呈现为:update "options" set "tally" = "tally" + 1 where "user_id" = ?

标签: javascript database postgresql knex.js


【解决方案1】:

您可以使用子查询来做到这一点:

knex('options')
  .increment('tally', 1)
  .whereIn('id', subQuery => {
    subQuery('options')
     .select('id')
     .where('user_id', user_id)
     .orderBy('tally', 'asc')
     .limit(1);
  })
  .then(option => {
    console.log(option);
    res.sendStatus(200);
  });

【讨论】:

  • 非常感谢!这就是我一直在寻找的。​​span>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2019-07-15
  • 2020-10-11
  • 1970-01-01
  • 1970-01-01
  • 2015-08-26
  • 2023-04-10
相关资源
最近更新 更多