mysql层次结构自连接,检索所有子类别

标签 mysql sql recursion

我有包含以下列的表 categories:

category_id
category_name
parent_id

我需要获取给定主类别的所有级别的所有子类别列表,因此,例如,如果我给出某个 3 级类别的 ID,我将返回所有 4、5、6 级类别的列表……是那个 lvl 3 类别的 child 。

不需要保留层次结构,只是一个简单的列表。

我首先想到的只是通过几个连接和子查询来完成它,但我认为之后类别会更深,所以这不是一个可行的方法。

由于我刚刚开始使用 SQL,我仍然不知道如何编写递归查询,所以这将是一个很好的帮助和学习 Material 。

最佳答案

首先阅读底部的请注意。好的好的,你回来了。

为类递归层次结构检索创建存储过程。

请注意,您不希望按级别进行,但这很容易完成。

架构:

create table category
(   category_id int not null auto_increment primary key,
    category_name varchar(40) not null,
    parent_id int null,  -- index on this column not a shabby idea
    unique key (category_name)
);

insert category(category_name,parent_id) values ('car',null),('food',null); -- 1,2
insert category(category_name,parent_id) values ('ford',1),('chevy',1),('fruit',2); -- 3,4,5
insert category(category_name,parent_id) values ('economy',3),('escort',6),('exhaust',7); -- 6,7,8
insert category(category_name,parent_id) values ('chassis',7),('loud',8),('banana',5); -- 9,10,11
-- ok granted I could have explicity inserted category_id to make it more obvious

创建存储过程:

-- drop procedure showHierarchyBelow;
delimiter $$
create procedure showHierarchyBelow
(
catname varchar(40)
)
BEGIN
    -- deleteMe parameter means i am anywhere in hierarchy of role
    -- and i want me and all my offspring deleted (no orphaning of children or theirs)
    declare bDoneYet boolean default false;
    declare working_on int;
    declare theCount int;
    declare findFirst int;

    select ifnull(category_id,0) into findFirst from category where category_name=catname;

    CREATE TABLE xx_RecursishHelper_xx
    (   -- it's recurshish, not recursive
        category_id int not null,
        processed int not null
    );
    if isnull(findFirst) then
        set findFirst=0;
    end if;
    insert into xx_RecursishHelper_xx (category_id,processed) select findFirst,0;
    if (findFirst=0) then
        set bDoneYet=true;
    else
        set bDoneYet=false;
    end if;

    while (!bDoneYet) do
        -- I am not proud of this next line, but oh well
        select count(*) into theCount from xx_RecursishHelper_xx where processed=0;

        if (theCount=0) then 
            -- found em all
            set bDoneYet=true;
        else
            -- one not processed yet, insert its children for processing
            SELECT category_id INTO working_on FROM xx_RecursishHelper_xx where processed=0 limit 1;
            insert into xx_RecursishHelper_xx (category_id,processed)
            select category_id,0 from category
            where parent_id=working_on;

            -- mark the one we "processed for children" as processed
            update xx_RecursishHelper_xx set processed=1 where category_id=working_on;
        end if;
    end while;

    delete from xx_RecursishHelper_xx where category_id=findFirst;

    select x.category_id,c.category_name
    from xx_RecursishHelper_xx x
    join category c
    on c.category_id=x.category_id;

    drop table xx_RecursishHelper_xx;
END
$$

测试存储过程:

call showHierarchyBelow('food');
+-------------+---------------+
| category_id | category_name |
+-------------+---------------+
|           5 | fruit         |
|          11 | banana        |
+-------------+---------------+

call showHierarchyBelow('car');
+-------------+---------------+
| category_id | category_name |
+-------------+---------------+
|           3 | ford          |
|           4 | chevy         |
|           6 | economy       |
|           7 | escort        |
|           8 | exhaust       |
|           9 | chassis       |
|          10 | loud          |
+-------------+---------------+

call showHierarchyBelow('ford');
+-------------+---------------+
| category_id | category_name |
+-------------+---------------+
|           6 | economy       |
|           7 | escort        |
|           8 | exhaust       |
|           9 | chassis       |
|          10 | loud          |
+-------------+---------------+

call showHierarchyBelow('xxx');
-- no rows

请注意,我只是修改了这个 Answer我几个月前的数据,可以满足您的需求。

请注意

以上仅供说明之用。在现实世界的情况下,我永远不会在存储过程中创建表。 DDL 开销很大。相反,我会使用带有 session 概念的预先存在的非临时表。并在完成的 session 中清除行。因此,不要将以上内容视为稻草人,等待您使其变得更加高效。询问这是否令人困惑。

关于mysql层次结构自连接,检索所有子类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31965365/

相关文章:

mysql - 需要显示来自 2 个单独表的匹配记录

SQL查询在单个事务中获取数据

mysql - 向大型数据库表正确添加索引

javascript - jquery如何传递上次迭代的变量?

mysql - #1064 - 你的 SQL 语法有错误;检查与您的 MariaDB 服务器版本对应的手册

php - 如何使用 PHP 将 Excel 数据导入 MySQL

mysql - 在 MySQL 中查找控制字符

mysql - 使用 MYSQL 创建随机数

PHP - 递归地从SQL数据库中获取数据

c++ - 无限循环问题