If you have only two columns, this is easy:
select distinct least(col1, col2), greatest(col1, col2)
from t;
With three, this is a bit harder:
select distinct least(no1, no2, no3) as smallest,
(case when no1 not in (least(no1, no2, no3), greatest(no1, no2, no3)) then no1
when no2 not in (least(no1, no2, no3), greatest(no1, no2, no3)) then no2
else no3
end) as middle,
greatest(no1, no2, no3) as biggest
from items;
Note that distinct
is a more succinct way of getting distinct groups.
EDIT:
If you want to do this for more columns, MySQL doesn't offer the nth()
function (analogous to least()
and greatest()
. You can do the following. Unpivot the values (assuming there is an id on each row), then use group_concat()
with the order by
option:
select distinct nos
from (select id, group_concat(noi order by noi) as nos
from (select id,
(case when n.n = 1 then no1
when n.n = 2 then no2
when n.n = 3 then no3
end) as noi
from items i cross join
(select 1 as n union all select 2 union all select 3) n
) nn
group by id
) nn;
This will give you back the values as a comma separated list.