在SQL中的有向图中计算不同的无向边

时间:2011-03-10 19:36:20

标签: sql postgresql directed-graph

给定一个在有向图中保持边的表,如下所示:

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

获取特定节点的不同无向链接数量的最佳方法是什么?没有任何重复的有向边,也没有任何节点直接链接到它们自己,我只是想避免计算两次重复的无向边(例如(1,2)(2,1))。

这有效,但NOT IN对我来说闻起来很糟糕:

SELECT COUNT(*)
FROM edges
WHERE from_here = 1
   OR (to_there = 1 AND from_here NOT IN (
        SELECT to_there 
        FROM edges 
        WHERE from_here = 1
   ))

PostgreSQL特定的解决方案对此很好。

3 个答案:

答案 0 :(得分:7)

如果情况是每个边缘都有一个倒数(例如,如果(1,2)存在,那么(2,1)必须存在),那么你可以简单地缩小你的列表:

 Select Count(*)
 From edges
 Where from_here < to_here
    And from_here = 1

如果我们不能假设互惠边总是存在,那么你可以使用Except谓词:

Select Count(*)
From    (
        Select from_here, to_there
        From edges
        Where from_here = 1
            Or to_there = 1
        Except
        Select to_there, from_here
        From edges
        Where from_here = 1
        ) As Z

答案 1 :(得分:6)

select count(*) from (
  select to_there from edges where from_here = 1
  union
  select from_here from edges where to_there = 1
) as whatever

答案 2 :(得分:1)

SELECT COUNT(DISTINCT CASE to_here WHEN 1 THEN from_here ELSE to_here END)
FROM edges
WHERE from_here = 1
   OR to_here = 1
/* or WHERE 1 IN (from_here, to_here) */