【问题标题】:save SELECT COUNT into variable using mysql and knex使用 mysql 和 knex 将 SELECT COUNT 保存到变量中
【发布时间】:2019-03-08 11:52:11
【问题描述】:

我想使用 knex 和 MySQL 进行计数并将计数值保存到变量中。下面是我的代码的 sn-p。我使用邮递员处理请求

router.post('/insertNewProject', (req, res) => {
    knex
      .raw('SELECT COUNT(id_proj) FROM project WHERE projectName=?', [req.body.projectName])
      .then((count) => {
        res.json(count[0])
      })
      .catch(() => {
        res.json({ success: false, message: "Please try again later." })
      })
})

这将返回我:

[
    {
        "COUNT(id_proj)": 0  //or 1 of the record is in table
    }
]

我的问题是如何将结果存储到变量中?根据select count 的结果,我想如果它是=0 进行查询,如果它大于0,则进行另一个查询。感谢您的宝贵时间!

【问题讨论】:

  • 这很简单。您只需访问 count(ip_proj) 值。然后你可以存储在一个变量中。试试这个var result = count[0].COUNT(id_proj);
  • 我已经尝试过了,但它不起作用。我试图把它放在then 中,但结果将是Please try again later.。你建议在哪里写?
  • 好的..!!@Tenzolinho
  • 阅读这篇文章也许会有所帮助zetcode.com/javascript/knex
  • 您的 COUNT(id_proj) 被用作 javascript 变量名,但由于括号的原因,它无法通过 javascript 点表示法访问。您可以使用:count[0]['COUNT(id_proj)'] 访问它,也可以更改查询以使用不同的变量名称,例如:SELECT COUNT(id_proj) AS CNT。 (虽然我更喜欢@saka7 的查询语法,因为它删除了查询的raw() 部分。)

标签: mysql node.js knex.js


【解决方案1】:

您的 knex 查询可能有错误,试试这个:

router.post('/insertNewProject', async (req, res) => {
    const result = await knex('project')
        .count('id_proj as count')
        .where({projectName: req.body.projectName})
        .first()
        .catch(() => res.json({
            success: false,
            message: "Please try again later."
        }));

    if (result.count === 0) {
        // Perform some query
        return res.json({/* Some response */});
    } else {
        // Perform another query
        return res.json({/* Some response */});
    }
});

【讨论】:

    【解决方案2】:

    我试图以不同的方式解决这个问题,摆脱了select count

     knex
        .select('*')
        .from('project')
        .where('projectName', '=', req.body.projectName)
        .then((count) => {
          if (count == 0) {
              // do query1
          } else {
              // do query2
          }
        })
        .catch(() => {
          res.json({ success: false, message: "Please try again later." })
        })
    

    希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-22
      • 2013-11-25
      • 1970-01-01
      相关资源
      最近更新 更多