Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

mysql - How to find unique pairs from two columns in SQL?

i have a table"Dummy" with columns "col1 and col2".

How do i find unique pairs from(col1,col2). For example in the above table how do i get (a,b) or (b,a) only as my output, instead of both (a,b) and (b,a).

select
    distinct
    col1
    col2
from
    dummy
where
    dummy.col1 < dummy.col2
group by
    col1,
    col2;

the above query is wrong as it missed out the pair (d,c).

Wrong query

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

i would rather use concat and group by

SELECT 
col1,col2 
FROM 
tbl
GROUP BY CONCAT(LEAST(col1, col2), 
              GREATEST(col1, col2))

OR SIMPLY

SELECT 
    col1,col2 
    FROM 
    tbl
group by LEAST(col1, col2),GREATEST(col1, col2)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...