mysql - 如何在 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 - 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/

相关文章:

MySQL 在插入和更新时自动递增

php - 打印指定行 mysql & PHP

mysql - SQL:选择行不属于同一表内条件的事务

MySQL 错误 #1415 - 不允许从函数返回结果集

java - 如果唯一键匹配,则跳过持久化实体

php - MySQL:根据同一表的一条记录中的一个选定字段中的值删除表中的多行

mysql - 在 Yii2 中访问具有多个(结果集)的存储过程的所有数据集

mysql - 从使用相同联接的多个表中进行选择

mysql - 将第二个字段与mysql查询中的第一个字段连接起来

php - Mysqli 不插入任何数据