Search code examples
mysqlsqldatabasedistinctdistinct-values

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.


Solution

  • 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