New feature of MySQL8 - common expression (CTE)

MySQL8.0 began to support common table expression (CTE) (common table expression), that is, the WITH clause.

Easy to get started:

The following SQL is a simple CTE expression, similar to a recursive call. In this SQL, first execute select 1 and then get the query result and send the value n to select n+1 under union all from cte where n <10, Then recursively call the following sql statement of union all in this way.

WITH recursive cte(n) as 
( select 1
  union ALL
  select n+1 from cte where n<10
)
select * from cte;

Case introduction:

A staff table contains id, name and m_id, which is the corresponding superior id. Data are as follows:

If we want to find out the superior-subordinate relationship of each employee, we can use the following method

Recursive CTE:

with recursive staff_view(id,name,m_id) as
(select id ,name ,cast(id as char(200)) 
 from staff where m_id =0
 union ALL 
 select s2.id ,s2.name,concat(s1.m_id,'-',s2.id)
 from staff_view as s1 join  staff as s2
 on s1.id = s2.m_id
)
select * from staff_view order by id

The advantage of using general table expressions is that even if there are 4, 5, 6 or even more layers in the upper and lower levels, it can help us traverse them, and the old way of writing SQL statements needs to be adjusted.

Summarize:

Common table expressions are similar to derived tables, like statement-level temporary tables or views. A CTE can be referenced multiple times in a query, it can reference other CTEs, it can be recursive. CTE supports SELECT/INSERT/UPDATE/DELETE and other statements.

Guess you like

Origin blog.csdn.net/m0_70299172/article/details/130496370