Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove opposite rows from SQL table

Tags:

sql

set

unordered

I have the following SQL table:

A|B
---
w|x
x|w
y|z
z|y

Can I construct a query which will yield the following result:

A|B
---
w|x
y|z

To summarize, I would like to treat the two columns as an unordered set, such that (a,b) == (b,a).

like image 533
CJH Avatar asked Apr 27 '26 15:04

CJH


1 Answers

The "best" code depends on the database, but following is dbms-agnostic:

SELECT      t.A,
            t.B
FROM        my_table t
LEFT JOIN   my_table t2
        ON  t.A = t2.B
        AND t.B = t2.A
        AND t.A < t.B
WHERE       t2.A IS NULL
like image 157
van Avatar answered Apr 30 '26 05:04

van