今天在sql训练题库中看到了这题,这是一道很有代表性的多表修改题,其实解出这道题并不难,无论是mysql中还是oracle中都有很多种解法,接下来就好好归纳一下这些解法。
msyql中多表修改
对于mysql中常用的多表修改语句,还是用例子来解释一下吧。
//建表 create table aaa(id int,value1 int(5),value2 int(5),value3 int(5),value4 int(5)); create table bbb like aaa; //插入数据 insert into aaa values(1,0,0,0,0),(2,0,0,0,0),(3,0,0,0,0),(4,0,0,0,0),(5,0,0,0,0),(6,0,0,0,0),(7,0,0,0,0); insert into bbb values(1,11,12,13,14),(3,31,32,33,34),(5,51,52,53,54); //备份 create table a1 select * from aaa; create table b1 select * from bbb;
一般多表修改:(在mysql和oracle中都适用,下面也会解释oracle中的)
//一般多表修改 update a1 set a1.value1 = (select b1.value1 from b1 where a1.id = b1.id), a1.value2 = (select b1.value2 from b1 where a1.id = b1.id);
表关联多表修改(这个只适用于mysql中)
//表关联多表修改 update a1 inner join b1 on a1.id = b1.id set a1.value1 = b1.value1, a1.value2 = b1.value2,a1.value3 = b1.value3;
oracle中多表修改
--建表 create table aaa(id number,value1 number,value2 number,value3 number,value4 number); create table bbb(id number,value1 number,value2 number,value3 number,value4 number); --插入数据 insert into aaa values(1,0,0,0,0);insert into aaa values(2,0,0,0,0);insert into aaa values(3,0,0,0,0); insert into aaa values(4,0,0,0,0);insert into aaa values(5,0,0,0,0);insert into aaa values(6,0,0,0,0); insert into aaa values(7,0,0,0,0);insert into bbb values(1,11,12,13,14); insert into bbb values(3,31,32,33,34);insert into bbb values(5,51,52,53,54); -- 备份 create table a1 as select * from aaa; create table b1 as select * from bbb;
一般多表修改:
和上面mysql中语句一样,这个写法比较容易理解,但是效率实在有些不尽人意,如果你们的多表修改只用修改一列(像最上面的那题一样),用这种写法挺好的。
//一般多表修改 update a1 set a1.value1 = (select b1.value1 from b1 where a1.id = b1.id), a1.value2 = (select b1.value2 from b1 where a1.id = b1.id);
但是涉及到了多列修改,用这个就不太现实了,在oracle中就提供了一种语法让我们去进行多表修改和新增。
merge into
merge into是update和insert语句的结合,可以同时实现update和insert的功能,在这里我就不多解释了,简单介绍一下merge into的语法吧。
merge into 目标表a ---into指向的目标表就是我们要做更新操作的表。 using 源表b ---using指向的表不能被更改,它还可以是视图、结果集等。 on(a.id = b.id) ---on()里面是用作目标表和源表匹配的条件,条件满足则匹配成功。 when matched then ---when matched then 后面接的是修改语句。 update set ... when not matched then ---when not matched then 后面接的是新增语句。 insert values(....);
merge into a1 using b1 on (a1.id = b1.id) when matched then update set a1.value1 = b1.value1,a1.value2 = b1.value2,a1.value3 = b1.value3;
exists多表修改
exists同样也适用于mysql和oracle,如果没有硬性要求表a根据表b的数据去修改,使用exists也是可以的。使用exists后的sql执行顺序是先执行外查询再执行内查询,所以多表修改就不能将表a1的值改为表a2的值。
update a1 set a1.value1 = 99,a1.value2 = 999,a1.vlaue3=999 where exists(select value1 from b1 where a1.id = b1.id);