SQL:在有向图中获取无向链接

时间:2014-08-22 13:19:13

标签: sql graph

我有一张在有向图中保持边缘的表格:

CREATE TABLE edges ( 
    from_here int not null, 
    to_there  int not null
)

如何在此表上选择忽略所有反向链接?例如,从这个表:

+------------+----------+--+
| from_there | to_there |  |
+------------+----------+--+
|          1 |        2 |  |
|          2 |        1 |  |
|          3 |        4 |  |
+------------+----------+--+

我想得到这个结果:

+------------+----------+--+
| from_there | to_there |  |
+------------+----------+--+
|          1 |        2 |  |
|          3 |        4 |  |
+------------+----------+--+

换句话说,我怎样才能获得每个双向链接只是前向链接?我们不能假设互惠边缘总是存在。

编辑目标是每个双向链接获得一行,无论是前向还是后向链接都无关紧要

1 个答案:

答案 0 :(得分:0)

如果我做对了

select from_there, to_there
from edges x
where not exists (
    select 1 from edges y 
    where x.from_there = y.to_there
      and x.to_there = y.from_there
      and x.to_there < y.to_there
);