[英]save SELECT COUNT into variable using mysql and knex
I want to do a count using knex and MySQL and save the count value into a variable. 我想使用knex和MySQL进行计数并将计数值保存到变量中。 Down below is a snippet of my code.
下面是我的代码片段。 I use postman for requests
我使用邮递员的请求
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." })
})
})
This will return me: 这会回报我:
[
{
"COUNT(id_proj)": 0 //or 1 of the record is in table
}
]
My question is how can I store the result into a variable? 我的问题是如何将结果存储到变量中? Based on the result of the
select count
, I want if it's =0
to do a query and if it's greater than 0, to do another query. 根据
select count
的结果,我想如果它是=0
来进行查询,如果它大于0,则进行另一个查询。 Thank you for your time! 感谢您的时间!
I tried to solve this in a different way, getting rid of select count
: 我尝试以不同的方式解决这个问题,摆脱
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." })
})
Hope this helps someone. 希望这有助于某人。
You probably have an error in your knex-query, try this: 您的knex-query中可能有错误,请尝试以下方法:
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 */});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.