SQL Graph 最短路径示例
Posted
技术标签:
【中文标题】SQL Graph 最短路径示例【英文标题】:SQL Graph shortest path example 【发布时间】:2020-01-26 17:28:56 【问题描述】:提供在 SQL Server 2019 上使用最短路径的示例。技术称为 SQL Graph。
Car -> BodyWork
|
V
Wheel -> Tyre
我们如何列出从根目录下来的所有部分和相关路径?
【问题讨论】:
您应该将其更多地表述为一个具体问题。即给出设置数据,然后问 - 我如何获得 X 和 Y 之间的最短路径? 【参考方案1】: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;
【讨论】:
以上是关于SQL Graph 最短路径示例的主要内容,如果未能解决你的问题,请参考以下文章