9

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

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 特定的解决方案对此很好。

4

3 回答 3

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
于 2011-03-10T20:01:48.340 回答
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
于 2011-03-10T19:54:33.687 回答
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) */
于 2012-04-27T10:07:56.663 回答