Second Brain: Crafted, Curated, Connected, Compounded on 10月02日 21:26
CTE类型及使用
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

本文介绍了CTE的概念、类型(递归和非递归)及其在SQL查询中的应用,以减少SQL语句的重复,并特别强调了递归CTE在处理层次结构数据时的优势。

A Common Table Expression (CTE) is a temporary, named result set, which can be referenced within SELECT, INSERT, UPDATE, or DELETE statements. CTEs are also usable in Views.

123
WITH cte_query AS(SELECT  subquery ...)SELECT main query ... FROM/JOIN with cte_query ...

# Types of CTEs: Recursive and Non-Recursive

# Non-Recursive CTE

There are two main types of CTEs: Recursive and Non-Recursive.

Non-recursive CTEs are simpler, used to reduce SQL duplication by replacing repeated SQL statements with a reference name.

Example:

12345678
WITH avg_per_store AS  (SELECT store, AVG(amount) AS average_order   FROM orders   GROUP BY store)SELECT o.id, o.store, o.amount, avg.average_order AS avg_for_storeFROM orders oJOIN avg_per_store avgON o.store = avg.store;

# Recursive CTE

Recursive CTEs incorporate repeated procedural loops, hence the term “recursive.” These CTEs call themselves until a specified condition is met. In a recursive CTE, a termination condition is crucial to avoid infinite recursion.

Recursive CTEs are particularly useful for querying hierarchical data, such as organizational charts (where employees report to managers) or multi-level bills of materials (where products comprise multiple components, each of which may also consist of other components).

 1 2 3 4 5 6 7 8 910111213141516171819202122
WITH levels AS (  SELECT    id,    first_name,    last_name,    superior_id,    1 AS level  FROM employees  WHERE superior_id IS NULL  UNION ALL  SELECT    employees.id,    employees.first_name,    employees.last_name,    employees.superior_id,    levels.level + 1  FROM employees, levels  WHERE employees.superior_id = levels.id) SELECT *FROM levels;

For more details, visit 5 Practical SQL CTE Examples | LearnSQL.com.


Origin: 5 Practical SQL CTE Examples | LearnSQL.com.
References:
Created 2023-10-31

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

CTE SQL 递归 非递归
相关文章