반응형
SQL: 인접 노드를 유향 그래프로 쿼리합니다.
노드가 있는 그래프가 있습니다.{A, B, C, D, ...}
테이블과 테이블 사이에 방향된 모서리를 지정합니다.
| node_1 | node_2 |
|-----------------|
| A | B |
| A | C |
| B | A |
| B | D |
| D | A |
우리는 글을 쓴다.A ~ B
에 대한 우위성이 있다면A
로.B
그래서 한바탕 소란을 피우고node_1 = A
그리고.node_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)
다음은 한 가지 방법입니다.
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
음...집약과 함께 조건부 논리를 사용할 수 있습니다.
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<>fiddle이 있습니다.
이것이 가장 심플하고 퍼포먼스가 뛰어난 솔루션이라고 생각됩니다.
언급URL : https://stackoverflow.com/questions/67746558/sql-query-adjacent-nodes-in-a-directed-graph
반응형
'itsource' 카테고리의 다른 글
개체를 어레이로 변환하려면 어떻게 해야 합니까? (0) | 2022.09.18 |
---|---|
Swisscom MariaDb Ent의 기본 테이블 스토리지 형식은 무엇입니까? (0) | 2022.09.18 |
HashMap Java 8 구현 (0) | 2022.09.18 |
입력 인수를 기반으로 한 모의 python 함수 (0) | 2022.09.18 |
Ruby on Rails 모델이 프리로드에 대해 인식되지 않습니까? (0) | 2022.09.18 |