mariadb SQL:查询有向图中的相邻节点

eanckbw9  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(133)

我有一个图,它的节点是{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)
7gs2gvoe

7gs2gvoe1#

这里有一种方法:

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
qlfbtfca

qlfbtfca2#

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

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);

这里有一个db〈〉小提琴。
这似乎是最简单的解决方案,也可能是性能最好的解决方案。

相关问题