小编典典

如何在MySql中使用递归查询?

mysql

    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-您的SQL语法有误;检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在“ RECURSIVEtransiveive_closure(a,b,distance,path_string)AS(SELECT a,b,1 A''第1行附近使用)

阅读 419

收藏
2020-05-17

共1个答案

小编典典

WITH RECURSIVE语句/方法适用于PostgreSQL和Sybase(我想可能还有更多),所以也许您可以看一下:

http://www.artfulsoftware.com/mysqlbook/sampler/mysqled1ch20.html

它应该向您展示一些使用MySQL的方法(以及PHP中的一两个方法,我只知道它不在您的标签列表中)

2020-05-17