node.js 如何使用 sequelize 获得一行的不同值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41519695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a distinct value of a row with sequelize?
提问by made_in_india
I have table with value
我有有价值的表
id country
1 india
2 usa
3 india
I need to find the distinct values from the country column using sequelize.js
我需要使用 sequelize.js 从 country 列中找到不同的值
here my sample code...
这是我的示例代码...
Project.findAll({
attributes: ['country'],
distinct: true
}).then(function(country) {
...............
});
Is there any way to find the distict values
有什么办法可以找到 distict 值
采纳答案by Maria Ines Parnisari
Try with this: https://github.com/sequelize/sequelize/issues/2996#issuecomment-141424712
试试这个:https: //github.com/sequelize/sequelize/issues/2996#issuecomment-141424712
Project.aggregate('country', 'DISTINCT', { plain: false })
.then(...)
回答by djones
You can specify distinct for one or more attributes using Sequelize.fn
您可以使用不同的方式为一个或多个属性指定不同的 Sequelize.fn
Project.findAll({
attributes: [
// specify an array where the first element is the SQL function and the second is the alias
[Sequelize.fn('DISTINCT', Sequelize.col('country')) ,'country'],
// specify any additional columns, e.g. country_code
// 'country_code'
]
}).then(function(country) { })
回答by Jurosh
I ended up using grouping like this:
我最终使用了这样的分组:
Project.findAll({
attributes: ['country'],
group: ['country']
}).then(projects =>
projects.map(project => project.country)
);
It results into distinct models you can nicely iterate.
它会生成不同的模型,您可以很好地迭代。
Link in previous answer helped little bit: https://github.com/sequelize/sequelize/issues/2996#issuecomment-141424712
先前答案中的链接有点帮助:https: //github.com/sequelize/sequelize/issues/2996#issuecomment-141424712
This works well too, but generating response with DISTINCT as column name:
这也很有效,但生成响应为 DISTINCT 作为列名:
Project.aggregate('country', 'DISTINCT', { plain: false })
.then(...)

