Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting distinct 2 columns combination in mysql

I have a mysql table that looks like this:

1   value1    value2    3534 2   value1    value1    8456 3   value1    value2    3566 4   value1    value3    7345 5   value2    value3    6734 

I need a query to select all the rows with distinct column 2 and 3, for example the output I want for this example will look like this:

1   value1    value2    3534 2   value1    value1    8456 4   value1    value3    7345 5   value2    value3    6734 

i've found a few samples on how to do it but they all select distinct on each column individually.

like image 986
James Harzs Avatar asked Jun 30 '12 20:06

James Harzs


People also ask

How do you find the distinct combination of two columns?

To select distinct combinations from two columns, you can use CASE statement.

How do I select distinct two columns in MySQL?

To select distinct values in two columns, you can use least() and greatest() function from MySQL.

How do you make a unique two column combination in SQL?

To define a UNIQUE on multiple columns, we put a comma-separated columns list inside parenthesis that follows the UNIQUE keyword.

Can you use select distinct with multiple columns?

Answer. Yes, the DISTINCT clause can be applied to any valid SELECT query. It is important to note that DISTINCT will filter out all rows that are not unique in terms of all selected columns. Feel free to test this out in the editor to see what happens!


2 Answers

Update 1

Better you use this against above.

SELECT id, col2, col3, col4 FROM yourtable GROUP BY col2, col3; 

Demo

The reason I am saying is because using CONCAT, I am not getting desired result in this case. First query is returning me 5 rows however CONCAT is returning me 4 rows which is INCORRECT.

Hope you got my point.


Assumed the columns in the table are (id, col2, col3, col4).

SELECT DISTINCT(CONCAT(col2, col3)) as "dummy column", id, col2, col3, col4 FROM yourtable GROUP BY CONCAT(col2, col3); 

OR

SELECT id, col2, col3, MIN(col4) FROM yourtable GROUP BY col2, col3; 

live working example

like image 182
Fahim Parkar Avatar answered Sep 25 '22 17:09

Fahim Parkar


Assuming that the first column is unique, you can do this:

SELECT id, col2, col3, col4 FROM yourtable WHERE id IN (     SELECT MIN(id)     FROM yourtable     GROUP BY col2, col3 ) 

See it working online: sqlfiddle

like image 41
Mark Byers Avatar answered Sep 23 '22 17:09

Mark Byers