WITH RECURSIVE transitive_closure(a, b, distance, path_string) AS
( SELECT a, b, 1 AS distance,
a || '.' || b || '.' AS path_string,
b AS direct_connection
FROM edges2
WHERE a = 1 -- set the starting node
UNION ALL
SELECT tc.a, e.b, tc.distance + 1,
tc.path_string || e.b || '.' AS path_string,
tc.direct_connection
FROM edges2 AS e
JOIN transitive_closure AS tc ON e.a = tc.b
WHERE tc.path_string NOT LIKE '%' || e.b || '.%'
AND tc.distance < 3
)
SELECT * FROM transitive_closure
--WHERE b=3 -- set the target node
ORDER BY a,b,distance
如何在 MySql 中运行此查询?
它会显示这样的错误信息:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'RECURSIVE transitive_closure(a, b, distance, path_string) AS ( SELECT a, b, 1 A' at line 1
最佳答案
WITH RECURSIVE
语句/方法适用于 PostgreSQL 和 Sybase(我想可能还有更多),所以也许你可以看看这个:
http://www.artfulsoftware.com/mysqlbook/sampler/mysqled1ch20.html
它应该向您展示一些使用 MySQL 的方法(以及 PHP 中的一两个方法,我知道它不在您的标签列表中)
关于mysql - 如何在 MySql 中使用递归查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8561654/