Home > Database > Mysql Tutorial > How Can I Replicate a Recursive MSSQL CTE Query for Building a Category Tree in MySQL?

How Can I Replicate a Recursive MSSQL CTE Query for Building a Category Tree in MySQL?

Mary-Kate Olsen
Release: 2024-12-01 08:54:13
Original
716 people have browsed it

How Can I Replicate a Recursive MSSQL CTE Query for Building a Category Tree in MySQL?

Transforming a MSSQL CTE Query to MySQL

In a MySQL schema with a 'category' table containing columns for id, parent id, and name, you wish to replicate a MSSQL CTE query that builds a category tree from the bottom up for a specified category ID. This query is as follows:

with CTE (id, pid, name)
as
(
    select id, parentid as pid,name
    from category
    where id = 197
      union all
        select CTE.pid as id , category.parentid as pid, category.name
        from CTE
          inner join category
            on category.id = CTE.pid
 )
 select * from CTE 
Copy after login

Unfortunately, MySQL lacks support for CTEs. As a result, using a subquery in place of them may not be an option because the CTE in question is a recursive one, referencing itself within the query. MySQL does not support recursive CTEs.

To achieve similar functionality, a stored procedure must be implemented. A previous answer on how to "Generate Depth based tree from Hierarchical Data in MySQL (no CTEs)" can serve as a starting point for crafting such a procedure.

The above is the detailed content of How Can I Replicate a Recursive MSSQL CTE Query for Building a Category Tree in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template