ORACLE WITH AS 用法

先举个例子吧:

有两张表,分别为A、B,求得一个字段的值先在表A中寻找,如果A表中存在数据,则输出A表的值;如果A表中不存在,则在B表中寻找,若B表中有相应记录,则输出B表的值;如果B表中也不存在,则输出"no records”字符串。

 

  1. with  
  2. sql1 as (select to_char(a) s_name from test_tempa),  
  3. sql2 as (select to_char(b) s_name from test_tempb where not exists (select s_name from sql1 where rownum=1))  
  4. select * from sql1  
  5. union all  
  6. select * from sql2  
  7. union all  
  8. select 'no records' from dual  
  9.        where not exists (select s_name from sql1 where rownum=1)  
  10.        and not exists (select s_name from sql2 where rownum=1);  

再举个简单的例子

with a as (select * from test)

select * from a;

其实就是把一大堆重复用到的SQL语句放在with as 里面,取一个别名,后面的查询就可以用它

这样对于大批量的SQL语句起到一个优化的作用,而且清楚明了

下面是搜索到的英文文档资料

About Oracle WITH clause 
Starting in Oracle9i release 2 we see an incorporation of the SQL-99 “WITH clause”, a tool for materializing subqueries to save Oracle from having to re-compute them multiple times.

The SQL “WITH clause” is very similar to the use of Global temporary tables (GTT), a technique that is often used to improve query speed for complex subqueries. Here are some important notes about the Oracle “WITH clause”:

   • The SQL “WITH clause” only works on Oracle 9i release 2 and beyond.
   • Formally, the “WITH clause” is called subquery factoring
   • The SQL “WITH clause” is used when a subquery is executed multiple times
   • Also useful for recursive queries (SQL-99, but not Oracle SQL)

To keep it simple, the following example only references the aggregations once, where the SQL “WITH clause” is normally used when an aggregation is referenced multiple times in a query. 
We can also use the SQL-99 “WITH clause” instead of temporary tables. The Oracle SQL “WITH clause” will compute the aggregation once, give it a name, and allow us to reference it (maybe multiple times), later in the query.

The SQL-99 “WITH clause” is very confusing at first because the SQL statement does not begin with the word SELECT. Instead, we use the “WITH clause” to start our SQL query, defining the aggregations, which can then be named in the main query as if they were “real” tables:

WITH 
subquery_name
AS
(the aggregation SQL statement)
SELECT
(query naming subquery_name);

Retuning to our oversimplified example, let’s replace the temporary tables with the SQL “WITH  clause”:

WITH
sum_sales AS 
  select  
    sum(quantity) all_sales from stores
number_stores AS 
  select  
    count(*) nbr_stores from stores
sales_by_store AS
  select  
  store_name, sum(quantity) store_sales from 
  store natural join sales
SELECT
   store_name
FROM
   store,
   sum_sales,
   number_stores,
   sales_by_store
where
   store_sales > (all_sales / nbr_stores)
;

Note the use of the Oracle undocumented “materialize” hint in the “WITH clause”. The Oracle materialize hint is used to ensure that the Oracle cost-based optimizer materializes the temporary tables that are created inside the “WITH” clause. This is not necessary in Oracle10g, but it helps ensure that the tables are only created one time.

It should be noted that the “WITH clause” does not yet fully-functional within Oracle SQL and it does not yet support the use of “WITH clause” replacement for “CONNECT BY” when performing recursive queries.

To see how the “WITH clause” is used in ANSI SQL-99 syntax, here is an excerpt from Jonathan Gennick’s great work “Understanding the WITH Clause” showing the use of the SQL-99 “WITH clause” to traverse a recursive bill-of-materials hierarchy
The SQL-99 “WITH clause” is very confusing at first because the SQL statement does not begin with the word SELECT. Instead, we use the “WITH clause” to start our SQL query, defining the aggregations, which can then be named in the main query as if they were “real” tables:

WITH 
subquery_name
AS
(the aggregation SQL statement)
SELECT
(query naming subquery_name);


Retuning to our oversimplified example, let’s replace the temporary tables with the SQL “WITH” clause”:

=================================================================================

下面自己小试一把,当然,一点都不复杂,很简单很简单的例子,呵呵。

 

  1. SQL> create table t2(id int);  
  2.   
  3. Table created.  
  4.   
  5. SQL> create table t3(id int);  
  6.   
  7. Table created.  
  8.   
  9. SQL> insert into t2 values(1);  
  10.   
  11. 1 row created.  
  12.   
  13. SQL> insert into t2 values(2);  
  14.   
  15. 1 row created.  
  16.   
  17. SQL> insert into t3 values(3);  
  18.   
  19. 1 row created.  
  20.   
  21. SQL> commit;  
  22.   
  23. Commit complete.  
  24.   
  25. SQL> select * from t2;  
  26.   
  27.         ID  
  28. ----------  
  29.          1  
  30.          2  
  31.   
  32. SQL> select * from t3;  
  33.   
  34.         ID  
  35. ----------  
  36.          3  
  37. SQL> with  
  38.   2  sql1 as (select * from t2),  
  39.   3  sql2 as (select * from t3)  
  40.   4  select * from t2  
  41.   5  union  
  42.   6  select * from t3;  
  43. sql2 as (select * from t3)  
  44.                        *  
  45. ERROR at line 3:  
  46. ORA-32035: unreferenced query name defined in WITH clause  
  47.   
  48. --从这里可以看到,你定义了sql1和sql2,就得用它们哦,不然会报错的。  
  49.   
  50. SQL> with  
  51.   2  sql1 as (select * from t2),  
  52.   3  sql2 as (select * from t3)  
  53.   4  select * from sql1  
  54.   5  union  
  55.   6  select * from sql2;  
  56.   
  57.         ID  
  58. ----------  
  59.          1  
  60.          2  
  61.          3  
  62.   
  63. --下面加个WHERE条件试试  
  64.   
  65. SQL> with  
  66.   2  sql1 as (select * from t2),  
  67.   3  sql2 as (select * from t3)  
  68.   4  select * from sql1  
  69.   5  union  
  70.   6  select * from sql2  
  71.   7  where id in(2,3);  
  72.   
  73.         ID  
  74. ----------  
  75.          1  
  76.          2  
  77.          3  
  78.   
  79. --奇怪?为什么加了WHERE条件还是输出ID=1的记录了,继续往下看:  
  80.   
  81. SQL> with  
  82.   2  sql1 as (select * from t2),  
  83.   3  sql2 as (select * from t3)  
  84.   4  select * from sql1  
  85.   5  where id=3  
  86.   6  union  
  87.   7  select * from sql2  
  88.   8  where id=3;  
  89.   
  90.         ID  
  91. ----------  
  92.          3  
  93.   
  94. --可以看到,每个条件是要针对每个SELECT语句的。  

好了就先记这些吧,以后看到了新的用法再补充。

Oracle数据库中,WITH AS语法也被称为公共表表达式(CTE),用于创建临时命名的结果集,这些结果集可以在后续的查询中引用。以下是其常见的使用方法: ### 基本用法 创建一个临时表 `t_a`,并对其进行查询,由于with as是内存中的table,所以查询速度相对较快,但数据量较大时不建议使用。示例代码如下: ```sql with t_a as( select 18 as age from dual union select 19 as age from dual union select 20 as age from dual ) select avg(age) from t_a; ``` 上述代码中,`t_a` 是临时表名,它包含了 `age` 列,最后对 `age` 列求平均值 [^2]。 ### 插入数据时使用 在向一张表插入数据时也可以使用 `WITH AS` 语法。示例代码如下: ```sql insert into table2 with s1 as ( select rownum c1 from dual connect by rownum <= 10), s2 as ( select rownum c2 from dual connect by rownum <= 10) select a.c1, b.c2 from s1 a, s2 b where ...; ``` 这里创建了两个临时表 `s1` 和 `s2`,并将它们连接后的结果插入到 `table2` 中 [^3]。 ### 多CTE联合使用 可以定义多个CTE,并在主查询中引用它们。示例代码如下: ```sql with dept_costs as ( select d.dname, sum(e.sal) dept_total from emp e, dept d where e.deptno = d.deptno group by d.dname ), avg_cost as ( select sum(dept_total) / count(1) avg from dept_costs ) select * from dept_costs where dept_total < (select avg from avg_cost); ``` 代码中定义了 `dept_costs` 和 `avg_cost` 两个CTE,主查询从 `dept_costs` 中筛选出部门总薪资小于平均薪资的记录 [^4]。 ### 用于复杂查询提高可读性 使用 `WITH AS` 可以将复杂的查询分解为多个简单的部分,提高查询的可读性和可维护性。示例代码如下: ```sql WITH department_avg_salary AS ( SELECT department_id, AVG(salary) AS avg_salary FROM employees GROUP BY department_id ) SELECT e.first_name, e.last_name, e.department_id, e.salary FROM employees e JOIN department_avg_salary d_avg ON e.department_id = d_avg.department_id WHERE e.salary > d_avg.avg_salary; ``` 这里先定义了 `department_avg_salary` CTE 计算每个部门的平均薪资,然后在主查询中筛选出薪资高于部门平均薪资的员工信息 [^5]。 ### 递归查询 CTE支持递归查询,适用于处理层次结构数据,如组织结构图、文件系统目录等。不过引用中未给出递归CTE的具体示例,以下是一个简单的递归CTE示例: ```sql WITH RECURSIVE cte_name AS ( -- 初始查询 SELECT 1 as num UNION ALL -- 递归部分 SELECT num + 1 FROM cte_name WHERE num < 10 ) SELECT * FROM cte_name; ``` 上述代码从 `1` 开始,每次递归将 `num` 加 `1`,直到 `num` 达到 `10` 为止。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值