MERGE 和 WITH语法

1. MERGE :可一次性实现对数据的 INSERT, UPDATE, DELETE等,用法如下:

SQL> select * from st_a;

ID          NAME
---------- ----------
1     F
100    Z

SQL> select * from st_b;

ID      NAME
---------- ----------
1     A
2     B
3     C
100    Z

SQL> merge into st_a a using st_b b on (a.id=b.id)
2 when matched then
3 update set a.name=b.name
4 delete where id=100
5 when not matched then
6 insert values (b.id,b.name);

4 rows merged.

SQL> select * from st_a;

ID    NAME
---------- ----------
1     A
2     B
3     C

SQL> 

2. WITH:定义的结果集,表名都是临时的,不存储在数据库中,可以将查询的结果集定义别名,用于SQL语句的调用

SQL> with temp_a as (select id,sum(sal) sumsal from st_a group by id) --注意逗号

2 temp_b as (select sum(sumsal)/count(*) avgsal from temp_a)

3 select * from temp_a where sumsal <(select avgsal from temp_b);

ID    SUMSAL
---------- ----------
1     7000

其中temp_a和temp_b是WITH语法定义的两个结果集名称,WITH语法后面只能紧跟SELECT语句,且中间不能有任何标点符号

原文地址:https://www.cnblogs.com/eniniemand/p/14057215.html