MySql 中的递归查询以确定继承类型

Recursive query in MySql to Determine Inheritance type

我有 table 有关可变数据类型的信息。称为 inheritance table,列 derivedbase 以及以下示例数据;

derived | base

 Double | Number
 Int    | Number
 Int64  | Int
 Number | Object

正如所见,可以有一些基本数据类型也属于派生列。但是保证没有循环依赖。我的目标是将输出作为两列 derivedbase,其中 base 列是相应派生类型的最终根基元素。

例如,Int64 的基数为 Int。我正在尝试使用 MySql 版本 >8.0 的递归。这是我的尝试;

WITH RECURSIVE hierarchy AS (
SELECT 
derived,
base 
 
FROM inheritance 

UNION ALL

SELECT

inheritance.derived,
inheritance.base
FROM inheritance,hierarchy
WHERE inheritance.derived = hierarchy.base)

SELECT *
FROM hierarchy;

我的终止宽恕似乎有错误,因此出现以下错误;

ERROR 3636 (HY000) at line 715: Recursive query aborted after 1001 iterations. Try increasing @@cte_max_recursion_depth to a larger value..

请注意,这只是示例数据,因此我正在尝试编写一个通用的递归查询。 Help/advice 表示赞赏。

您的查询不应产生此类错误;您的数据中可能存在循环依赖,您需要先修复它。

那么,你似乎想要:

with recursive hierarchy as (
    select derived, base, 1 lvl from inheritance
    union all
    select h.derived, i.base, h.lvl + 1
    from hierarchy h
    inner join inheritance i on i.derived = h.base
)
select derived, base
from hierarchy h
where lvl = (select max(h1.lvl) from hierarchy h1 where h1.derived = h.derived)

理由:

  • 您想在爬升层次结构时跟踪原始derived

  • 递归查询每个中间层生成一行;外部查询中需要额外的逻辑来仅保留“最深”的父级

Demo on DB Fiddle 包含原始查询和新查询