Treat the table as a variable to implement recursive calling and level traversal

In the previous article, we discussed how to use SQL set operators (UNION [ALL], INTERSECT, and EXCEPT) to combine multiple query results into one result.

Next we introduce a very powerful feature in SQL: Common Table Expression (Common Table Expression).

Table as variable

In programming languages, variables and functions (methods) are usually defined; variables can be reused, and functions (methods) can modularize the code and improve the readability and maintainability of the program.

Similarly, the general table expressions in SQL can realize the reuse of query results, simplify complex join queries and subqueries; and can complete data recursive processing and hierarchical traversal .

The following is an example from Part 17, using a subquery to return the average monthly salary of each department:

SELECT d.dept_name AS "部门名称",
       ds.avg_salary AS "平均月薪"
  FROM department d
  LEFT JOIN (SELECT dept_id,
                    AVG(salary) AS avg_salary
               FROM employee
              GROUP BY dept_id) ds
    ON (d.dept_id = ds.dept_id);

Among them, the result ds of the subquery is equivalent to a temporary table. The result of this query is as follows:

with

We can use a general table expression to rewrite the example as follows:

WITH ds(dept_id, avg_salary) AS 

Guess you like

Origin blog.csdn.net/horses/article/details/108729097