oracle笔记:merge into 的使用、删除重复项保留一条、null、''空字符串、' '空格的注意事项

个人笔记记录:

oracle 联表多字段更新,使用 merge into 语句执行速度快很多

慢:

update tableA set (a1,a2,a3)=(select b1,b2,b3 from tableB where ...) where ...  

快:

merge into tableA a
using (select b1,b2,b3 from tableB where ...) b
on (条件)	                --这里面添加条件,多个条件用 and 连接,eq:a.a4=b.b4
when matched then
update....../insert.........	--满足条件时执行,eq:update set a.a1=b.b1
when not matched then
update....../insert.........	--不满足条件时执行

oracle 查询(删除)重复项,保留rowid最小的一条:

select * from 表 a where (a.Id,a.seq) in (select Id,seq from 表 group by Id,seq having count(*) > 1) 
    and rowid not in (select min(rowid) from 表 group by Id,seq having count(*)>1)

oracle 查询语句选择:

慢:	select a.tel,(select name from b where b.tel=a.tel) name from a
快:	select a.tel,b.name from a,b where a.tel=b.tel
oracle 中,null、''空字符串、' '空格的注意事项:

参考:http://www.cnblogs.com/memory4young/p/use-null-empty-space-in-oracle.html

--建表
create table tbl_a (col_a varchar2(1), col_b int);  
--  造数据
insert into tbl_a values(' ', 1); 	--  插入空格
insert into tbl_a values('', 2); 	--  插入空字符串
insert into tbl_a values(null, 3); 	--  插入NULL

执行select来检查:

select count(*) from tbl_a; 			   -- 结果是 3 
select count(*) from tbl_a where col_a =  ' ';     -- 结果是 1 
select count(*) from tbl_a where col_a =  '';      -- 结果是 0 
select count(*) from tbl_a where col_a is null;    -- 结果是 2 

注意:由于 '' (空串)默认被转换成了 null, 不能使用 = '' 作为查询条件,也不能用 is ''。虽不会有语法错误,但查询结果会有误。只能用 is null 或者 is not null 。

not in 查不到应有的结果:(不返回字段为null的结果)

如下语句,查不出表中包含null的数据(即,查不在 tableB 的号码时,不返回号码为null的结果)

select * from tableA a where phone not in (select phone from tableB b where ...)

下语句,能够返回号码为null的数据

select * from tableA a where phone not exists (select phone from tableB b where ...)
提示:当 ‘not in’ 子查询里面有null时,结果集不返回null;in、exists、not exists子查询中是否有null值结果集都正常

 
 

你可能感兴趣的:(oracle)