【问题标题】:SQL: get undirected links in directed graphSQL:在有向图中获取无向链接
【发布时间】:2014-08-22 13:19:12
【问题描述】:

我有一个表格,在有向图中保存边:

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 |  |
+------------+----------+--+

换句话说,我如何才能为每个双向链接获取正向链接?我们不能假设互易边总是存在的。

EDIT目标是每个双向链接获得一行,无论是前向链接还是后向链接

【问题讨论】:

  • 你如何决定哪个是前向链接?在上面的例子中,为什么返回 1-2 而不是 2-1?
  • 没关系,我更新了问题

标签: sql graph


【解决方案1】:

如果我猜对了

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
);

【讨论】:

  • 谢谢,但这些数字不按任何顺序排列,我们不能指望它们升序
  • 您必须以某种方式选择边缘 (1,2) 或 (2,1) 之一。在我的建议中(1,2)被选中。如果您更改为x.to_there &gt; y.to_there,您将获得 (2,1)
猜你喜欢
  • 1970-01-01
  • 2012-12-20
  • 2013-11-14
  • 2011-11-23
  • 2014-06-29
  • 2015-07-18
  • 2014-08-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多