Files
blog-press/docs/Web/MySQL/SQL-Advance.md
2026-05-20 11:26:38 +08:00

41 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: SQL高阶用法
date: 2025-12-21
---
# 一、WITH
## 1.1 定义
  SQL 中的WITH子句也被称为**公用表表达式**CTECommon Table Expression它的作用是**在执行主查询之前,先定义一个临时的结果集,这个结果集可以在后续的查询中被多次引用**,就像一个临时表一样。它能让复杂的 SQL 查询变得更清晰、更易读,还能简化嵌套查询的逻辑。
## 1.2 使用
```sql
-- 定义第一个CTE数学高分学生
WITH math_high_score AS (
SELECT name, score FROM student_score WHERE subject = '数学' AND score > 85
),
-- 定义第二个CTE语文高分学生
chinese_high_score AS (
SELECT name, score FROM student_score WHERE subject = '语文' AND score > 85
)
-- 主查询:查询既在数学高分又在语文高分的学生
SELECT m.name
FROM math_high_score m
JOIN chinese_high_score c ON m.name = c.name;
```
  递归 CTE
```sql
WITH recursive dept_hierarchy AS (
-- 锚点成员查询顶级部门parent_id为NULL
SELECT dept_id, dept_name, parent_id, 1 AS level
FROM department
WHERE parent_id IS NULL
UNION ALL
-- 递归成员查询子部门关联自身的dept_id和parent_id
SELECT d.dept_id, d.dept_name, d.parent_id, dh.level + 1 AS level
FROM department d
JOIN dept_hierarchy dh ON d.parent_id = dh.dept_id
)
-- 主查询:获取所有部门的层级
SELECT * FROM dept_hierarchy;
```