如何使用sequelize获取行的明确值?

mad*_*dia 8 node.js express sequelize.js

我有价值的桌子

id country 
1  india
2  usa
3  india
Run Code Online (Sandbox Code Playgroud)

我需要使用sequelize.js从country列中找到不同的值

这是我的示例代码......

Project.findAll({

    attributes: ['country'],
    distinct: true
}).then(function(country) {
     ...............
});
Run Code Online (Sandbox Code Playgroud)

有没有办法找到distict值

小智 33

您可以使用指定一个或多个属性的distinct 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) {  })
Run Code Online (Sandbox Code Playgroud)

  • SequelizeDatabaseError:"DISTINCT"或其附近的语法错误 (9认同)
  • 使用MySQL时,此解决方案有效-确保将DISTINCT字段用作第一个属性。 (4认同)
  • 如果您不包含另一个模型,则上述语法有效,在添加包含时它会抛出“SequelizeDatabaseError:位于或接近“DISTINCT”的语法错误” (3认同)

Jur*_*osh 16

我最终使用了这样的分组:

Project.findAll({
  attributes: ['country'],
  group: ['country']
}).then(projects => 
  projects.map(project => project.country)
);
Run Code Online (Sandbox Code Playgroud)

它会生成不同的模型,您可以很好地迭代。

先前答案中的链接有点帮助:https : //github.com/sequelize/sequelize/issues/2996#issuecomment-141424712

这也很有效,但生成响应为 DISTINCT 作为列名:

Project.aggregate('country', 'DISTINCT', { plain: false })
  .then(...)
Run Code Online (Sandbox Code Playgroud)


Mar*_*ari 9

试试这个:https://github.com/sequelize/sequelize/issues/2996#issuecomment-141424712

Project.aggregate('country', 'DISTINCT', { plain: false })
.then(...)
Run Code Online (Sandbox Code Playgroud)

  • 你怎么能确保它是独特的而且是最新的(通过 createdAt) (3认同)
  • 您如何为“ DISTINCT”列名加上别名?它返回一个表,其中列名是“ DISTINCT” (2认同)