SQL中使用update inner join和delete inner join;Oracle delete join替代方案
Update
Update XXX set XXX where 这种写法大家肯定都知道,才发现update和delete居然支持inner join的update方式,这个在表间关联来做更新和删除操作非常有用.
例子:
Sql代码
update tb_User
set pass='' --此处pass前不要加 tb_User 别名usr
from tb_User usr
inner join tb_Address addr on usr.nAddressFK = addr.nAddressID
where usr.id=123
update的格式是
update t1 set t1.name=’Liu’ from t1 inner join t2 on t1.id = t2.tid
MySQL,ACCESS 写法如下:
Sql代码
UPDATE mem_world AS mw1 INNER JOIN mem_world AS mw2
ON mw1.parentid = mw2.wid
SET mw1.level = mw2.level
WHERE mw2.baseid = 107
AND mw2.parentid = 0
AND mw2.size > 1;
on是表连接的筛选条件 就是说,表连接后,会产生一个类似于临时的视图这么一个东西
where是从这个临时的视图中筛选数据的
所以,你首先要搞清,你的所谓的2个条件属于哪一种
Delete
delete 语句也是类似
delete from t1 from t1 inner join t2 on t1.id = t2.tid
注意蓝色部分。
mysql:
Sql代码
DELETE mwb FROM mem_world_building AS mwb INNER JOIN mem_world AS mw
ON mwb.wid = mw.wid
where mw.type between 11 and 15
and baseid = 107
and mw.parentid <> 0
and mw.size > 1;
下面是Oracle的:
Sql代码
DELETE TABLE1 where KHID exists ( select KHID from table2 where FWDWID=8)
Sql代码
DELETE TABLE1 where exists ( select 1 from table2 where and table1.khid=table2.khid and FWDWID=8);
delete from A where sid in
(select a.sid from A a inner join B b on a.num2 = b.num1
where b.num2 not between '10'and '10000') 这段sql如何优化,不使用in?
1. 用exists 来替代 in
delete
from
A
where
exists
(
select
1
from
B b
where
A.num2 = b.num1
where
b.num2
not
between
'10'
and
'10000'
);
不过你用not between,估计效率就不怎么好了。
2. 在 A 的num2,B的num1、num2上都 建立索引。
上一篇:oracle top 替代方案
下一篇:oracle group 取每组第一条