【问题标题】:Recursive query in MySql to Determine Inheritance typeMySql中的递归查询以确定继承类型
【发布时间】:2020-10-11 23:09:47
【问题描述】:

我有关于可变数据类型信息的表格。名为inheritance 的表,包含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..

请注意,这只是示例数据,因此我正在尝试编写一个通用递归查询。感谢您的帮助/建议。

【问题讨论】:

  • 我测试了您显示的内容,但没有出现错误。我正在使用 MySQL 8.0.21。您使用的是哪个版本?
  • 我猜你的数据与你展示的四行样本数据不同,你的继承中可能有一个循环。
  • 请提供样本数据和期望的结果。

标签: mysql sql hierarchical-data recursive-query


【解决方案1】:

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

那么,你似乎想要:

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 包含原始查询和新查询

【讨论】:

  • @GMB 感谢您的回复。这说得通。我想知道,如果我只想修改 base 为 Number 的那些行,我可以只过滤外部查询,而不是采用最深层次。您能确认一下吗?
猜你喜欢
  • 1970-01-01
  • 2011-09-03
  • 2023-03-12
  • 1970-01-01
  • 2017-12-23
  • 1970-01-01
  • 2011-06-20
  • 1970-01-01
  • 2016-03-18
相关资源
最近更新 更多