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

mu *_*ort 9 sql postgresql directed-graph

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

CREATE TABLE edges ( 
    from_here int not null, 
    to_there  int not null
)
Run Code Online (Sandbox Code Playgroud)

获取特定节点的不同无向链接数量的最佳方法是什么?没有任何重复的有向边,也没有任何节点直接链接到它们自己,我只是想避免计算重复的无向边(例如(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
   ))
Run Code Online (Sandbox Code Playgroud)

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

Tho*_*mas 7

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

 Select Count(*)
 From edges
 Where from_here < to_here
    And from_here = 1
Run Code Online (Sandbox Code Playgroud)

如果我们不能假设一个倒数边总是存在,那么你可以使用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
Run Code Online (Sandbox Code Playgroud)


ara*_*nid 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
Run Code Online (Sandbox Code Playgroud)