oracle中with的用法-Oracle
WITH 子句在 Oracle 中的用法
什么是 WITH 子句?
WITH 子句在 Oracle 中用于创建临时表或视图,这些表或视图仅在当前会话中可见。
语法
WITH clause_name AS (subquery) SELECT ... FROM ...
登录后复制
- clause_name:临时表或视图的名称。
- subquery:查询语句,用于创建临时表或视图。
用法
WITH 子句通常用于以下场景:
- 创建复杂的临时表或视图,用于查询中。
- 将复杂查询的结果重命名为更简单的名称,便于后续引用。
- 提高查询性能,通过将子查询的结果存储在临时表中。
示例
创建临时表
WITH EmployeeTemp AS ( SELECT employee_id, salary, department_id FROM Employees WHERE salary > 10000 ) SELECT * FROM EmployeeTemp;
登录后复制
重命名查询结果
WITH EmployeeSalaries AS ( SELECT employee_id, salary FROM Employees ) SELECT employee_id, salary AS emp_salary FROM EmployeeSalaries;
登录后复制
提高查询性能
WITH EmployeeAvgSalary AS ( SELECT department_id, AVG(salary) AS avg_salary FROM Employees GROUP BY department_id ) SELECT * FROM EmployeeAvgSalary WHERE avg_salary > 50000;
登录后复制