Home > Database > Mysql Tutorial > body text

Oracle中merge命令的简单使用

WBOY
Release: 2016-06-07 16:08:55
Original
1297 people have browsed it

通过这个merge你能够在一个SQL语句中对一个表同时执行inserts和updates操作,如果只是希望将源表中符合条件的数据合并到目标表中

merge命令

通过这个merge你能够在一个SQL语句中对一个表同时执行inserts和updates操作

使用meger语句,可以对指定的两个表执行合并操作,其语法如下:
MEGER INTO table1_name
USING table2_name ON join_condition
WHEN MATCHEO THEN UPDATE SET...
WHEN NOT MATCHED THEN INSERT ...VALUES...
语法说明如下:
table1_name表示需要合并的目标表。
table2_name表示需要合并的源表。
join_condition表示合并条件。
when matcheo then update表示如果符合合并的条件,则执行更新操作。
when not matched then insert表示如果不符合条件,则执行插入操作。

update和insert
    如果只是希望将源表中符合条件的数据合并到目标表中,可以只使用update子句,如果希望将源表中不符合合并条件的数据合并到目标表中,可以只使用insert子句。
    在update子句和insert子句中,都可以使用where子句指定更新过插入的条件。这时,对于合并操作来说,提供了两层过滤条件,第一层是合并条件,由meger子句中的on子句指定,第二层是update或insert子句中指定的where条件。从而使得合并操作更加灵活和精细。
在这里我们创建两张表,一张为person表,另一张为newpersono表,,两张表的结构是相同的
SQL> create table person(
  2  pid number(4),
  3  page number(3)
  4  );
表已创建。
--插入三行数据
SQL> insert into person values(1,20);
已创建 1 行。
SQL> insert into person values(2,21);
已创建 1 行。
SQL> insert into person values(3,22);
已创建 1 行。
SQL> create table newperson(
  2  pid number(4),
  3  page number(3)
  4  );
表已创建。
--插入三行数据
SQL> insert into newperson values(1,100);
已创建 1 行。
SQL> insert into newperson values(4,100);
已创建 1 行。
SQL> insert into newperson values(5,100);
已创建 1 行。
SQL> select * from person;


      PID      PAGE
---------- ----------
        1        20
        2        21
        3        22
SQL> select * from newperson;
      PID      PAGE
---------- ----------
        1        100
        4        100
        5        100
SQL> merge into person p1
  2  using newperson p2
  3  on (p1.pid=p2.pid)
  4  when matched then
  5    update set p1.page=p2.page
  6  when not matched then
  7    insert (pid,page) values(p2.pid,p2.page);


3 行已合并。
--上面的sql语句为当person中的pid等于newperson中的pid时,把person中的对应的page置为newperson中的age,当不符合时,向person插入不符合条件的数据。执行的结果如下:
SQL> select * from person;
      PID      PAGE
---------- ----------
        1        100
        2        21
        3        22
        5        100
        4        100
--newperson表中的数据不会改变:
SQL> select * from newperson;
      PID      PAGE
---------- ----------
        1        100
        4        100
        5        100

本文永久更新链接地址

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!