【问题标题】:PHP + MySQLi - no idea how to query DB to solve my problemPHP + MySQLi - 不知道如何查询数据库来解决我的问题
【发布时间】:2020-08-01 19:55:29
【问题描述】:

我有以下 MySQLi-DB:


    ╔═════════════╦═══════════╦════════════════╗
    ║ category_id ║ parent_id ║ name           ║
    ╠═════════════╬═══════════╬════════════════╣
    ║ 28          ║ 1         ║ blog root      ║
    ╠═════════════╬═══════════╬════════════════╣
    ║ 30          ║ 28        ║ painting       ║
    ╠═════════════╬═══════════╬════════════════╣
    ║ 31          ║ 30        ║ kids painting  ║
    ╠═════════════╬═══════════╬════════════════╣
    ║ 32          ║ 30        ║ teens painting ║
    ╠═════════════╬═══════════╬════════════════╣
    ║ 35          ║ 28        ║ recipes        ║
    ╠═════════════╬═══════════╬════════════════╣
    ║ 36          ║ 28        ║ diy            ║
    ╚═════════════╩═══════════╩════════════════╝

这是分类树


    blog root
        painting
            kids painting
            teens painting
        recipes
        diy

我需要创建一个查询,该查询将生成一个包含所有子类别的类别的所有 category_id。

示例:

1) query with category_id = 30 --> result 30, 31, 32
2) query with category_id = 28 --> result 28, 30, 31, 32, 35, 36
3) query with category_id = 35 --> result 35

我的新手查询是:

SELECT `category_id` FROM `blog_category` WHERE `category_id` = 28 OR `parent_id` = 28

这将导致 28、30、35、36 --> 缺少 31、32

我该如何解决这个问题?

编辑: 在 MySQL 中似乎不可能。

那么我如何使用 PHP 和简单的 Mysql-queries 创建一个逗号分隔的字符串来执行最终查询,例如 this solution on stackoverflow?

--->

... WHERE category_id IN ('$string')

【问题讨论】:

    标签: php mysql sql recursive-query


    【解决方案1】:

    您通常会使用递归查询来遍历层次结构树。此功能仅在 MySQL 8.0 中可用:

    with recursive cte as (
        select category_id, parent_id, name, 1 lvl from mytable where category_id = 28
        union all
        select t.category_id, t.parent_id, t.name, c.lvl + 1
        from cte c
        inner join mytable t on t.parent_id = c.category_id
    )
    select * from cte order by lvl, category_id
    

    这为每个孩子提供一行,按深度增加排序,然后按category_id

    如果您想要一个逗号分隔值而不是一组行,那么您只需将查询的最后一部分更改为使用聚合:

    select group_concat(category_id order by lvl, category_id) all_category_ids
    from cte
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-03
      • 1970-01-01
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 2023-01-30
      相关资源
      最近更新 更多