Domanda

Ho la seguente tabella SQL:

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

Posso creare una query che produrrà il seguente risultato:

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

Riassumendo, desidero trattare i due colonne come un insieme non ordinato, tale che (a, b) == (b, a).

È stato utile?

Soluzione

"migliore" di codice dipende dal database, ma che segue è 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

Altri suggerimenti

Si potrebbe provare il seguente:

SELECT LEAST(a,b) a, GREATEST(a,b) b
FROM t
GROUP BY LEAST(a,b), GREATEST(a,b)

Con il seguente test-table t:

CREATE TABLE t ( a VARCHAR(1), b VARCHAR(1) );

INSERT INTO t VALUES ('w','x'),('x','w'),('y','z'),('z','y');

restituisce:

w  x
y  z

Utilizzando LEAST e GREATEST rende anche sicuro che w x viene restituito al posto di x w.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top