如何将MSSQL CTE查询转换为MySQL?

问题描述 投票:25回答:3

在我的MySQL架构中,我有category(id, parentid, name)

在MSSQL中,我有CTE查询(从下到上为所提供的类别ID构建一个类别树:

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 

如何将该查询“转换”为MySQL?

mysql sql-server common-table-expression adjacency-list
3个回答
32
投票

不幸的是MySQL不支持CTE(公用表表达式)。这是早就应该的IMO。通常,您可以只使用子查询,但这个特定的CTE是递归的:它在查询中引用自身。递归CTE对于分层数据非常有用,但同样重要:MySql根本不支持它们。您必须实现存储过程才能获得相同的结果。

我之前的答案应该提供一个很好的起点:

Generating Depth based tree from Hierarchical Data in MySQL (no CTEs)


3
投票

值得庆幸的是,不再需要了,因为MySQL从8.0.1 supports CTE开始。


0
投票

遗憾的是MYSQl或XAMPP(MARIADB)mysql不支持CTE(COMMON TABLE EXPRESSIONS),因为你必须使用嵌套查询。

欲了解更多信息,请点击以下链接: -

https://mariadb.com/kb/en/library/with/

© www.soinside.com 2019 - 2024. All rights reserved.