Selecting distinct 2 columns combination in mysql

时光毁灭记忆、已成空白 提交于 2019-11-27 04:27:28

问题


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.


回答1:


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




回答2:


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




回答3:


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



回答4:


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



回答5:


THe simplest query for this is

SELECT col1, col2, MIN(col3)
FROM myTable
GROUP BY col1, col2



回答6:


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
)


来源:https://stackoverflow.com/questions/11277251/selecting-distinct-2-columns-combination-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!