Oracle常用Sql--初级

Select的执行顺序
sql的书写顺序为:select--from--where--group by--having--order by
Sql的执行顺序为:from--where--group by--having--select--order by
from:需要从哪个数据表检索数据
where:过滤表中数据的条件
group by:将上面过滤出的数据分组
having:对已经分组的数据进行进一步的过滤
select:从筛选完的数据中选择输入信息
order by :将输出信息进行排序

如何只显示重复数据,或不显示重复数据?
只显示重复数据:select * from tablename where (column1,column2...) in(select column1,column2... from tablename group by column1,column2… having count(*)>1);
不显示重复数据:select * from tablename where (column1,column2...) in(select column1,column2... from tablename group by column1,column2… having count(*)=1;

删除表中多余的重复记录
delete from tablename where (column1,column2...) in (select column1,column2... from tablename group by column1,column2... having count(*)>1) and rowid not in(select min(rowid) from tablename group by column1,column2... having count(*)>1)

nvl函数的应用
pers表中有两列salary(工资,不可为空)bonus(奖金,可为空),编号persid=1salary的值为2000bonus的值为null,写sql计算这个人的年薪。
错误的写法:select salary*12+bonus*12 from pers where persid=1;--此语句执行结果为null
正确的写法:select salary*12+nvl(bonus,0)*12 from pers where persid=1;

分页语句
有排序:
    SELECT * FROM  (  SELECT A.*, ROWNUM RN  FROM (SELECT * FROM TABLE_NAME where … order by …) A  WHERE ROWNUM <= 40  )  WHERE RN >= 21  ;
无排序:
    Select * from (select a.*,rownum rn from tablename where … and rownum<=40) where rn>=21;

Escape转义
查询表empname列中含有”_”的记录
Select * from emp where name like ‘%\_% ’ escape ‘\’;--“_”不在是通配符,而是其实际所代表的意义

关于null
null只能通过is null或者is not null来判断,其它操作符与null操作都是false
如:在product表中有一列为price(该列可为空),当需要查找price不为1000的记录时,sql语句应该这样写:select * from product where nvl(price,0)<>1000; 是如果直接这样写:select * from product where price<>1000,price值的为null的记录不会显示出来。

使用子查询更新数据
Update emp
  set(name,job,salary)=(select name,job,salary from emp where empnum=111)
where departmentid=(select departmentid from department where departregion=‘北京’)

在update语句中,子查询即可以用在where子句中,也可以用在set子句中
当需要进行表间或表内数据复制的时候该语句很有用

使用子查询创建表
create table tempacct as select * from acct;
或者
create table tempacct(acctnbr,acctname) as select acctnbr,acctname from acct;
利用该语句可以实现表克隆,即可以全表克隆,也可以部分克隆,如果select语句是多张表的关联查询,那也可以多表克隆。

多表插入
insert all 
  when acctnbr = 10 then into acct1 
  when acctnbr = 20 then into acct2 
  when acctnbr = 30 then into acct3 
  else into acct_other 
select * from acct;
或者
insert first
  when acctnbr = 10 then into acct1 
  when acctnbr = 20 then into acct2 
  when acctnbr = 30 then into acct3 
  else into acct_other 
select * from acct;
多表插入允许在一个sql语句中将查询结果集依条件插入到不同的表中,insert all和insert first的区别在于:前者允许一条记录同时插入多张表中,只要满足条件即插入;而后者具有排他性,满足一个条件之后就不再参与后续的判断。这 类似于JMS中发布-订阅模型和队列模型之间的差别。

Count()注意事项
select count(*) from test where ...
select count(column1) from test where...
同样的where条件,得出的查询结果可能不同,后者可能少于前者,因为当在count()函数中确切指定一个列的时候,数据库会忽略掉值为的null的记录。



猜你喜欢

转载自blog.csdn.net/lubiaopan/article/details/15341687