【问题标题】:SQL: Query adjacent nodes in a directed graphSQL:查询有向图中的相邻节点
【发布时间】:2021-05-28 23:48:10
【问题描述】:

我有一个带有节点 {A, B, C, D, ...} 的图和一个指定它们之间有向边的表。

| node_1 | node_2 |
|-----------------|
|      A | B      |
|      A | C      |
|      B | A      |
|      B | D      |
|      D | A      |

如果从AB 有一条边,我们写A ~ B。所以node_1 = Anode_2 = B 意味着A ~ B 的行。我区分以下类型的关系:

A = B if A ~ B and B ~ A
A > B if A ~ B and not B ~ A
A < B if B ~ A and not A ~ B

如何检索与给定节点相邻的所有节点及其关系类型?例如,对上表中A 的查询应返回

| node | type |
|------|------|
|    B | =    | (because A ~ B and B ~ A)
|    C | >    | (because A ~ C and not C ~ A)
|    D | <    | (because D ~ A and not A ~ D)
 

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。
  • 您好,能否请您附上您目前尝试过的代码。

标签: mysql sql mariadb


【解决方案1】:

这是一种方法:

select 
 node, 
 case when count(*) = 2 then '=' 
 when max(ordertype) = 1 then '>'
 when max(ordertype) = 2 then '<'
 end as type
from (
select node2 node,1 ordertype from nodes 
where node1 = 'A'
union all 
select node1,2 from nodes 
where node2 = 'A'
) t 
group by node 
order by node 

【讨论】:

    【解决方案2】:

    嗯。 . .您可以将条件逻辑与聚合一起使用:

    select (case when node_1 = 'A' then node_2 else node_1 end) as other_node,
           (case when count(*) = 2 then '='
                 when max(node_1) = 'A' then '>'
                 else '<'
            end) as type
    from nodes n
    where 'A' in (node_1, node_2)
    group by (case when node_1 = 'A' then node_2 else node_1 end);
    

    Here 是一个 dbfiddle。

    这似乎是最简单也可能是最高效的解决方案。

    【讨论】:

      猜你喜欢
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      相关资源
      最近更新 更多