给定一个包含有向图中边的表格,如下所示:
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 特定的解决方案很适合这个。
最佳答案
如果每条边都存在倒数(例如,如果 (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
关于sql - 计算 SQL 中有向图中不同的无向边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5264902/