公用表达式(Common Table Expressions, CTEs)是SQL中的一个特性,它允许你创建一个临时的结果集,然后在查询中多次引用这个结果集。CTE可以让查询更加模块化,使得复杂查询更易于理解和维护。
MySQL和SQL Server都支持CTE,但是在语法上有些许差异。
MySQL的CTE语法如下:
WITH cte_name (column1, column2, ...) AS (
SELECT column1, column2, ...
FROM table1
WHERE condition
)
SELECT column1, column2, ...
FROM cte_name;
SQL Server的CTE语法如下:
WITH cte_name (column1, column2, ...) AS (
SELECT column1, column2, ...
FROM table1
WHERE condition
)
SELECT column1, column2, ...
FROM cte_name;
两者在语法上基本一致,都是使用WITH
关键字开头,后面跟随CTE的名称和列名,接着是一个SELECT语句,最后是使用CTE的SELECT语句。
以下是一个简单的例子,使用CTE来计算员工的薪水,并按薪水进行排序:
MySQL:
WITH salaries AS (
SELECT employee_id, salary, department_id, salary * (1 + IFNULL(bonus, 0)) AS total_salary
FROM employees
JOIN departments ON employees.department_id = departments.department_id
)
SELECT *
FROM salaries
ORDER BY total_salary DESC;
SQL Server:
WITH salaries AS (
SELECT employee_id, salary, department_id, salary * (1 + ISNULL(bonus, 0)) AS total_salary
FROM employees
JOIN departments ON employees.department_id = departments.department_id
)
SELECT *
FROM salaries
ORDER BY total_salary DESC;
在这个例子中,CTE salaries
被用来计算每个员工的总薪水(基本薪水加上奖金),然后外部查询从CTE中选择数据并按照总薪水降序排序。