Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to select all columns of a table with unique combination of just some of them in MySQL?

I have a MySQL table named "Products" with the following structure:

id | name   | variety      | t_min | t_max | entity
====================================================
1  | hake   | salmo salar  | -5.27 | 10.3  | entity1
2  | salmon | null         | -2.45 | 12.9  | entity1
3  | cod    | gadus morhua | -4.98 | 11.98 | entity1
4  | hake   | salmo salar  | -7.87 | 9.35  | entity1
5  | hake   | salmo salar  | -2.76 | 8.46  | entity1

The desired result I would want is:

id | name   | variety      | t_min | t_max | entity
====================================================
1  | hake   | salmo salar  | -5.27 | 10.3  | entity1
2  | salmon | null         | -2.45 | 12.9  | entity1
3  | cod    | gadus morhua | -4.98 | 11.98 | entity1

I want to select all the columns of the table but avoid repeating rows that have the same name+variety in this case. Just using DISTINCT clause doesn’t work because if I use it I just can select the columns I want to be unique, so how can I do it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use window function

select *
from (
  select *, row_number() over(partition by name, variety order by id) rn
  from products
) r 
where r.rn = 1
order by r.id
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading