Selecting distinct 2 columns combination in mysql

前端 未结 6 1636
日久生厌
日久生厌 2020-12-03 03:13

I have a mysql table that looks like this:

1   value1    value2    3534
2   value1    value1    8456
3   value1    value2    3566
4   value1    value3    734         


        
相关标签:
6条回答
  • 2020-12-03 03:23

    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

    0 讨论(0)
  • 2020-12-03 03:24

    Using the group by method is returning me extra rows, where as explicitly checking each field although longer returns the same no of records as count(Distinct ..)

    SELECT id, col2, col3, col4
    FROM yourtable yt
    WHERE id =
    (
     SELECT MIN(id)
     FROM yourtable yt1
     WHERE yt.col2 = yt1.col2
     AND yt.col3 = yt1.col3
    )
    
    0 讨论(0)
  • 2020-12-03 03:28

    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

    0 讨论(0)
  • 2020-12-03 03:31

    This query makes sure that the combination of column1 and column2 is unique, while selecting the minimum value of column three

    SELECT col1, col2, MIN(col3)
    FROM yourTable
    GROUP BY col1, col2
    
    0 讨论(0)
  • 2020-12-03 03:38

    Assuming the columns in the table are (id, col1, col2, col3), you could:

    SELECT  *
    FROM    YourTable yt
    JOIN    (
            SELECT  MIN(id) as minid
            FROM    YourTable
            GROUP BY
                    col1, col2
            ) filter
    ON      filter.minid = yt.id
    
    0 讨论(0)
  • 2020-12-03 03:40

    THe simplest query for this is

    SELECT col1, col2, MIN(col3)
    FROM myTable
    GROUP BY col1, col2
    
    0 讨论(0)
提交回复
热议问题