Selecting distinct 2 columns combination in mysql

亡梦爱人 提交于 2019-11-27 20:32:26

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

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

Andomar

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

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

THe simplest query for this is

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

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