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

标签 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 特定的解决方案很适合这个。

最佳答案

如果每条边都存在倒数(例如,如果 (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/

相关文章:

postgresql - psql shell 命令执行与\!

sql - 在 Postgres 中嵌套或引用查询

postgresql - pgpoolAdmin 无法在步骤 2 之后继续

c++ - 在有向图中只访问一次所有节点

MySQL SQL 多

mySQL查询代码和索引优化

SQL Server 插入示例

mysql - 使用 LEFT OUTER JOIN 检查相关行不存在的最佳方法是什么

algorithm - Tarjan 的强连通分量算法——为什么索引在后边?

c - 有向未加权图 C