-4

提供在 SQL Server 2019 上使用最短路径的示例。技术称为 SQL Graph。

Car -> BodyWork
 |
 V
Wheel -> Tyre

我们如何列出从根目录下来的所有部分和相关路径?

4

1 回答 1

0
CREATE TABLE PRODUCT (
       ProductID int not null identity primary key,
       ProductName varchar(50) 
) AS Node;

INSERT INTO PRODUCT(ProductName) VALUES ('Car'),('BodyWork'),('Wheel'),('Tyre');

SELECT * FROM PRODUCT;

CREATE TABLE HAS_PART AS EDGE;


INSERT INTO HAS_PART ($from_id, $to_id)
VALUES ((SELECT $node_id FROM PRODUCT WHERE ProductId=1), (SELECT $node_id FROM PRODUCT WHERE ProductId=2))
,((SELECT $node_id FROM PRODUCT WHERE ProductId=1), (SELECT $node_id FROM PRODUCT WHERE ProductId=3))
,((SELECT $node_id FROM PRODUCT WHERE ProductId=3), (SELECT $node_id FROM PRODUCT WHERE ProductId=4));

SELECT * FROM HAS_PART;

SELECT
       P1.ProductID,
       P1.ProductName,
       COUNT(P2.ProductName) WITHIN GROUP (GRAPH PATH) AS [Depth],
       STRING_AGG(P2.ProductName,'->') WITHIN GROUP (GRAPH PATH) AS [Assembly],
       LAST_VALUE(P2.ProductID) WITHIN GROUP (GRAPH PATH) AS [Final Product ID]
FROM
       PRODUCT P1,
       PRODUCT FOR PATH P2,
       HAS_PART FOR PATH HP
WHERE MATCH(SHORTEST_PATH(P1(-(HP)->P2)+))
AND P1.ProductID = 1
ORDER BY P1.ProductID;

在此处输入图像描述

于 2019-09-26T12:22:55.893 回答