Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a distinct value of a row with sequelize?

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

here my sample code...

Project.findAll({      attributes: ['country'],     distinct: true }).then(function(country) {      ............... }); 

Is there any way to find the distict values

like image 261
made_in_india Avatar asked Jan 07 '17 09:01

made_in_india


People also ask

How do I get distinct rows in Sequelize?

You can use the the group option, however to avoid the MySQL error incompatible with sql_mode=only_full_group_by you must apply the MAX function to others attributes. Show activity on this post. You can use raw queries to get the result or sequelize. fn() .

How do you count distinct values in Sequelize?

count , you can just add any kind of aggregate function arguments supported by MYSQL to your options object. The following code will give you the amount of different values in MyModel 's someColumn : MyModel. count({distinct: 'someColumn', where: {...}}) .

How can I see unique values in MySQL?

To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns. The column names has to be separated with comma.


2 Answers

You can specify distinct for one or more attributes using 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) {  }) 
like image 65
djones Avatar answered Oct 16 '22 12:10

djones


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

This works well too, but generating response with DISTINCT as column name:

Project.aggregate('country', 'DISTINCT', { plain: false })   .then(...) 
like image 35
Jurosh Avatar answered Oct 16 '22 13:10

Jurosh