如何创建MySQL分层递归查询

如何创建MySQL分层递归查询

本文介绍了如何创建MySQL分层递归查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的MySQL表:

I have a MySQL table which is as follows:

19 category1 0
20 category2 19
21 category3 20
22 category4 21
... ... ...

现在,我想有一个MySQL查询,只需向其提供ID [例如说 id = 19 ],然后就应该获取其所有子ID [即结果的ID应该为'20,21,22']....

Now, I want to have a single MySQL query to which I simply supply the id [for instance say id=19] then I should get all its child ids [i.e. result should have ids '20,21,22']....

孩子的等级未知;可能会有所不同....

The hierarchy of the children is not known; it can vary....

我知道如何使用 for 循环来执行此操作...但是如何使用单个MySQL查询来实现相同功能?

I know how to do it using a for loop... but how to achieve the same using a single MySQL query?

推荐答案

对于 MySQL 8 +::使用递归 with 语法.
对于 MySQL 5.x::使用内联变量,路径ID或自联接.

For MySQL 8+: use the recursive with syntax.
For MySQL 5.x: use inline variables, path IDs, or self-joins.

with recursive cte (id, name, parent_id) as (
  select     id,
             name,
             parent_id
  from       products
  where      parent_id = 19
  union all
  select     p.id,
             p.name,
             p.parent_id
  from       products p
  inner join cte
          on p.parent_id = cte.id
)
select * from cte;

parent_id = 19 中指定的值应设置为要选择其所有后代的父级的 id .

The value specified in parent_id = 19 should be set to the id of the parent you want to select all the descendants of.

对于不支持通用表表达式的MySQL版本(最高5.7版),您可以通过以下查询来实现:

For MySQL versions that do not support Common Table Expressions (up to version 5.7), you would achieve this with the following query:

select  id,
        name,
        parent_id
from    (select * from products
         order by parent_id, id) products_sorted,
        (select @pv := '19') initialisation
where   find_in_set(parent_id, @pv)
and     length(@pv := concat(@pv, ',', id))

这里是小提琴.

在这里,在 @pv:='19'中指定的值应设置为要选择其所有后代的父级的 id .

Here, the value specified in @pv := '19' should be set to the id of the parent you want to select all the descendants of.

如果父母有多个孩子,这也将起作用.但是,要求每个记录都满足条件 parent_id<ID ,否则结果将不完整.

This will work also if a parent has multiple children. However, it is required that each record fulfills the condition parent_id < id, otherwise the results will not be complete.

此查询使用特定的MySQL语法:在执行过程中分配和修改变量.对执行顺序进行了一些假设:

This query uses specific MySQL syntax: variables are assigned and modified during its execution. Some assumptions are made about the order of execution:

  • from 子句首先被评估.这就是 @pv 初始化的地方.
  • 按照从 from 别名中检索的顺序,为每个记录评估 where 子句.因此,在这里将条件放在仅包括已将其父级标识为后代树的记录中(主要父级的所有后代都逐渐添加到 @pv 中).
  • where 子句中的条件按顺序求值,一旦确定总结果,就中断该求值.因此,第二个条件必须排在第二位,因为它将 id 添加到父列表中,并且只有在 id 通过第一个条件的情况下,才会发生这种情况.仅调用 length 函数以确保此条件始终为true,即使 pv 字符串由于某种原因会产生虚假的值.
  • The from clause is evaluated first. So that is where @pv gets initialised.
  • The where clause is evaluated for each record in the order of retrieval from the from aliases. So this is where a condition is put to only include records for which the parent was already identified as being in the descendant tree (all descendants of the primary parent are progressively added to @pv).
  • The conditions in this where clause are evaluated in order, and the evaluation is interrupted once the total outcome is certain. Therefore the second condition must be in second place, as it adds the id to the parent list, and this should only happen if the id passes the first condition. The length function is only called to make sure this condition is always true, even if the pv string would for some reason yield a falsy value.

总而言之,人们可能会发现这些假设过于冒险,无法依靠.文档警告:

All in all, one may find these assumptions too risky to rely on. The documentation warns:

因此,即使它与上面的查询一致地工作,评估顺序仍可能会更改,例如,当您添加条件或将此查询用作较大查询中的视图或子查询时.这是特征".将在将来的MySQL版本中删除:

So even though it works consistently with the above query, the evaluation order may still change, for instance when you add conditions or use this query as a view or sub-query in a larger query. It is a "feature" that will be removed in a future MySQL release:

如上所述,从MySQL 8.0起,您应该使用递归 with 语法.

As stated above, from MySQL 8.0 onward you should use the recursive with syntax.

对于非常大的数据集,此解决方案可能会变慢,因为 find_in_set 操作不是在列表中查找数字的最理想方法,当然,在列表中找到的数字与数量级相同的数量级也不是最理想的方法.返回的记录数.

For very large data sets this solution might get slow, as the find_in_set operation is not the most ideal way to find a number in a list, certainly not in a list that reaches a size in the same order of magnitude as the number of records returned.

越来越多的数据库实现了 SQL:1999 ISO标准 [RECURSIVE]语法用于递归查询(例如 Postgres 8.4+ SQL Server 2005 + DB2 Oracle 11gR2 + SQLite 3.8.4+ Firebird 2.1+ H2 HyperSQL 2.1.0+ Teradata MariaDB 10.2.2+ ).从版本8.0开始,MySQL也支持它.有关使用的语法,请参见此答案的顶部.

More and more databases implement the SQL:1999 ISO standard WITH [RECURSIVE] syntax for recursive queries (e.g. Postgres 8.4+, SQL Server 2005+, DB2, Oracle 11gR2+, SQLite 3.8.4+, Firebird 2.1+, H2, HyperSQL 2.1.0+, Teradata, MariaDB 10.2.2+). And as of version 8.0, also MySQL supports it. See the top of this answer for the syntax to use.

某些数据库具有用于分层查找的替代非标准语法,例如CONNECT BY 子句/B19306_01/server.102/b14200/queries003.htm"rel =" noreferrer> Oracle , DB2 Informix CUBRID 和其他数据库.

Some databases have an alternative, non-standard syntax for hierarchical look-ups, such as the CONNECT BY clause available on Oracle, DB2, Informix, CUBRID and other databases.

MySQL 5.7版不提供此功能.如果您的数据库引擎提供了这种语法,或者您可以迁移到该语法,那么这无疑是最佳选择.如果没有,请考虑以下替代方法.

MySQL version 5.7 does not offer such a feature. When your database engine provides this syntax or you can migrate to one that does, then that is certainly the best option to go for. If not, then also consider the following alternatives.

如果您要分配包含分层信息(路径)的 id 值,事情就会变得容易得多.例如,在您的情况下,可能看起来像这样:

Things become a lot easier if you would assign id values that contain the hierarchical information: a path. For example, in your case this could look like this:

19 category1
19/1 category2
19/1/1 category3
19/1/1/1 category4

然后您的 select 如下所示:

select  id,
        name
from    products
where   id like '19/%'

替代3:重复的自我联接

如果您知道层次结构树的深度上限,则可以使用标准的 sql 查询,如下所示:

select      p6.parent_id as parent6_id,
            p5.parent_id as parent5_id,
            p4.parent_id as parent4_id,
            p3.parent_id as parent3_id,
            p2.parent_id as parent2_id,
            p1.parent_id as parent_id,
            p1.id as product_id,
            p1.name
from        products p1
left join   products p2 on p2.id = p1.parent_id
left join   products p3 on p3.id = p2.parent_id
left join   products p4 on p4.id = p3.parent_id
left join   products p5 on p5.id = p4.parent_id
left join   products p6 on p6.id = p5.parent_id
where       19 in (p1.parent_id,
                   p2.parent_id,
                   p3.parent_id,
                   p4.parent_id,
                   p5.parent_id,
                   p6.parent_id)
order       by 1, 2, 3, 4, 5, 6, 7;

请参见小提琴

where 条件指定要检索其后代的父级.您可以根据需要将查询扩展到更多级别.

The where condition specifies which parent you want to retrieve the descendants of. You can extend this query with more levels as needed.

这篇关于如何创建MySQL分层递归查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 07:36