gpt4 book ai didi

sql - 使用 sequelize 使用 where 查询编码计数

转载 作者:行者123 更新时间:2023-12-03 22:19:07 29 4
gpt4 key购买 nike

我想通过使用 sequelize 和 node.js 将这个查询更改为代码取决于在哪里

select COUNT(gender) as genderCount from customers where gender = "male"
但我不知道如何添加
这个原始代码:
 Customer.findAll({
attributes: {
include: [[Sequelize.fn("COUNT", Sequelize.col("gender")), "genderCount"]] }
}).then(data => {
res.send(data)
})

最佳答案

对于 "sequelize": "^5.21.3" :
选项1。

const customers = await Customer.findAll({
attributes: [[Sequelize.fn('COUNT', Sequelize.col('gender')), 'genderCount']],
where: {
gender: 'male',
},
raw: true,
});
执行结果:
Executing (default): SELECT COUNT("gender") AS "genderCount" FROM "customers" AS "Customer" WHERE "Customer"."gender" = 'male';
[ { genderCount: '3' } ]
选项 2. 您可以使用 Model.count()

Count the number of records matching the provided where clause.


const customers = await Customer.count({ col: 'gender', where: { gender: 'male' } });
执行结果:
Executing (default): SELECT count("gender") AS "count" FROM "customers" AS "Customer" WHERE "Customer"."gender" = 'male';
以上示例基于数据库中的数据记录:
enter image description here

关于sql - 使用 sequelize 使用 where 查询编码计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65404394/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com