MySQL - 如何使表反对称

时间:2014-05-31 13:32:13

标签: mysql sql

我有下表:

f1 | f2
---+----
a  | b
b  | a
b  | c

预期结果:

f1 | f2
---+----
a  | b
b  | c

OR

f1 | f2
---+----
b  | a
b  | c

如果选择(a,b),则不应选择(b,a)

1 个答案:

答案 0 :(得分:1)

您可以使用distinctgroup by使用least()greatest()功能执行此操作。如:

select distinct least(f1, f2) as f1, greatest(f1, f2) as f2
from table t;

如果你热衷于确保配对实际上在原始表中(所以(c,b)无法选择 - 虽然它不适用于你给出的例子),那么你可以这样做: / p>

select f1, f2
from table t
where f1 < f2 or
      not exists (select 1 from table t2 where t2.f1 = t.f2 and t2.f1 = t.f1);