tags:

views:

46

answers:

3
+1  Q: 

2-column distinct?

I'm trying to select two distinct numbers id1 and id2 from the following table:

tb_table1( bigint id1 bigint id2 bigint userid)

if I do

select distinct id1, id2 from tb_table1 

I'll get, for example, two rows, (111, 222) and (222,111).

I only want one of those rows since I don't care which column, id1, or id2 that the result gets returned in. Basically, I want distinct pairs where order doesn't matter.

Thoughts? Thanks in advance.

+3  A: 

It would be remiss of me to not point out that this suggests your table is not quite as normalized as it should be - what will you do when users acquire a third id? But anyway.

Using the fact that UNION (as opposed to UNION ALL) will automatically de-duplicate, you could do

SELECT id1, id2 FROM tb_table1 WHERE id1 < id2
UNION
SELECT id2, id1 FROM tb_table1 WHERE NOT id1 < id2
AakashM
Rows where `id1 is null` or `id2 is null` will not be included in the results. Depending on requirements and definition of `id1` and `id2` that may or may not be an issue.
Shannon Severance
A: 

I think there is a better solution but this should work:

select t1.id1, t2.id2 
from tb_table1 t1
inner join tb_table1 t2 on t1.id1 = t2.id2 and t1.id2 = t2.id1
where t2.id1 is null
Fabian
A: 

would something like this be any help...

SELECT DISTINCT CASE WHEN id1 < id2 THEN id1 ELSE id2,
                CASE WHEN id1 > id2 THEN id1 ELSE id2
    FROM tb_table1;

(Having seen AakashM's solution, though, I think I like it better).

Brian Hooper