Oracle SQL 3则

Oracle SQL 3则

  • 如果存在就更新,不存在就插入用一个语句实现
MERGE  INTO  t_mg a
USING (
SELECT   ' the code '  code,  ' the name '  NAME  FROM  dual) b
ON  (a.code  =  b.code)
WHEN  MATCHED  THEN
UPDATE   SET  a.NAME  =  b.NAME
WHEN   NOT  MATCHED  THEN
INSERT  (code, NAME)  VALUES  (b.code, b.NAME);
  • 分页算法

SELECT   *
FROM  ( SELECT  a. * , ROWNUM rn
FROM  ( SELECT   *   FROM  t_employees  ORDER   BY  first_name) a
WHERE  ROWNUM  <=   500 )
WHERE  rn  >   480  ;

  • 抽取/删除重复记录

1) 部分字段重复数据的删除

delete   from  表名 a 
where  a.rowid  !=  
(
select   max (b.rowid)  from  表名 b 
where  a.字段1  =  b.字段1  and  
a.字段2 
=  b.字段2 
)

上面语句的执行效率是很低的,可以考虑建立临时表,讲需要判断重复的字段、rowid插入临时表中,然后删除的时候在进行比较。

create   table  临时表  as  
select  a.字段1,a.字段2, MAX (a.ROWID) dataid  from  正式表 a  GROUP   BY  a.字段1,a.字段2;
delete   from  表名 a 
where  a.rowid  !=  
(
select  b.dataid  from  临时表 b 
where  a.字段1  =  b.字段1  and  
a.字段2 
=  b.字段2 
)

2) 完全重复记录的删除

用下面语句获取到去掉重复数据后的记录:

select   distinct   *   from  表名

可以将查询的记录放到临时表中,然后再将原来的表记录删除,最后将临时表的数据导回原来的表中。如下:

CREATE   TABLE  临时表  AS  ( select   distinct   *   from  表名);
drop   table  正式表;
insert   into  正式表 ( select   *   from  临时表);
drop   table  临时表;

你可能感兴趣的:(Oracle SQL 3则)