简体   繁体   English

Sequelize:从多列中选择不同的字段值

[英]Sequelize: Selecting distinct field values from multiple columns

I'm using sequelize and mysql2 and need to select all the distinct values from multiple columns.我正在使用 sequelize 和 mysql2 并且需要从多个列中选择所有不同的值。 For example I've a 'Title' and a 'Location' column.例如,我有一个“标题”和一个“位置”列。

At the moment this:目前这个:

Job.findAll({
    attributes: [
        [Sequelize.fn('DISTINCT', Sequelize.col('title')), 'title']
    ]
})

works, returning all the job titles that are distinct.工作,返回所有不同的职位。 But if I add a second line for the location column I get a syntax error但是,如果我为位置列添加第二行,则会出现语法错误

Job.findAll({
    attributes: [
        [Sequelize.fn('DISTINCT', Sequelize.col('title')), 'title'],
        [Sequelize.fn('DISTINCT', Sequelize.col('location')), 'location']
    ]
})

It feels like it should work, from what I've read in the docs at least - but I'm not exactly experienced or confident with sequelize, so any help would be appreciated.感觉它应该有效,至少从我在文档中读到的内容来看 - 但我对续集并不完全有经验或信心,所以任何帮助将不胜感激。

Thanks谢谢

I haven't yet found a way to do this less-hackily, but you can exploit the fact that DISTINCT isn't really a function, but a statement and always operates on the entirety of the selected column set:我还没有找到一种不那么简单的方法,但是您可以利用 DISTINCT 不是真正的函数,而是一个语句并且始终对整个选定列集进行操作的事实:

Job.findAll({
    attributes: [
        [Sequelize.fn('DISTINCT', Sequelize.col('title')), 'title'],
        'location'
    ]
})

would generate SQL similar to将生成类似于

SELECT DISTINCT(`title`) AS `title`, `location` FROM `Jobs`;

but since DISTINCT is not a function, this is really the same as但由于 DISTINCT 不是函数,这实际上与

SELECT DISTINCT (`title`) AS `title`, `location` FROM `Jobs`;

which does do what you want because parenthesis around column names are optional, that query up there would be the same as这确实做你想做的,因为列名周围的括号是可选的,那里的查询将与

SELECT DISTINCT `title`, `location` FROM `Jobs`;

Source: https://dzone.com/articles/sql-distinct-is-not-a-function (the article also talks about the DISTINCT ON PostgreSQL extension, if someone happens to need that too)来源: https : //dzone.com/articles/sql-distinct-is-not-a-function (文章还谈到了 DISTINCT ON PostgreSQL 扩展,如果有人也需要的话)

Please note that this feels very hacky and sort of fragile and could/might break if Sequelize ever decides to change the way functions are applied when generating the SQL, but it works in the version of Sequelize I use (5.22.3).请注意,如果 Sequelize 决定更改生成 SQL 时应用函数的方式,这感觉非常笨拙且有点脆弱,并且可能/可能会中断,但它在我使用的 Sequelize 版本 (5.22.3) 中有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM