Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform a MSSQL CTE query to MySQL?

in my MySQL schema, I have the category(id, parentid, name) table

In the MSSQL, I have that CTE query (to build a category tree from the bottom up for a supplied category 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  

How to 'transform' that query to MySQL ?

like image 314
Tony Avatar asked Jan 12 '12 10:01

Tony


People also ask

Can CTE be used in MySQL?

Common Table Expression (CTE) is an important feature of MySQL that is used to generate a temporary result set. It can be used with any SQL statement like SELECT, INSERT, UPDATE, etc. The complicated queries can be simplified by using CTE.

Can you create table from CTE?

You can use a common table expression (CTE) to simplify creating a view or table, selecting data, or inserting data. Use a CTE to create a table based on another table that you select using the CREATE TABLE AS SELECT (CTAS) clause.

What is the disadvantage of CTE in SQL Server?

Disadvantages of CTECTE's members cannot use the following clauses of keywords Distinct, Group By, Having, Top, Joins limiting by this type of the queries that can be created and reducing their complexity. The Recursive member can refer to the CTE only once.

Why is CTE used in MySQL?

A CTE provides better readability and also increases the performance as compared to the derived table. Unlike a derived table, a CTE is a subquery that can be self-referencing using its own name. It is also known as recursive CTE and can also be referenced multiple times in the same query.


2 Answers

Unfortunately MySQL doesn't support CTE (Common Table Expressions). This is long overdue IMO. Often, you can just use a subquery instead, but this particular CTE is recursive: it refers to itself inside the query. Recursive CTE's are extremely useful for hierarchical data, but again: MySql doesn't support them at all. You have to implement a stored procedure to get the same results.

A previous answer of mine should provide a good starting point:

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

like image 161
Jon Black Avatar answered Sep 21 '22 09:09

Jon Black


Thankfully it's not necessary anymore, as MySQL starting from 8.0.1 supports CTE.

like image 27
Hubbitus Avatar answered Sep 24 '22 09:09

Hubbitus