oracle基础知识
常规
- 生成表空间
eg:create tablespace bbb
datafile ‘c:\aaa.dbf’
size 100m
autoextend on
next 10m;
释义 :创建表空间bbb,文件为aaa.dbf存储在c盘下,默认大小100M,超出默认每次自增10M; - 建立表应该指定表的表空间;
- 创建用户:create user 用户名 identified by 密码 default tablespace 表空间名字;
- 授权用户:grant dba/resource/connect to 用户名;
- 查询数据:select *,max(某字段) from 表名 where 条件 group by 某字段 order by 某字段 having 某条件;
- 修改某字段数据类型:alter table 表名 modify (字段名 数据类型);
- 修改数据:update 表名 set 字段名=值 where 条件;
- 删除某字段:alter table 表名 delete column 字段名;
- 添加外键:alter table A表 add constraint 外键名字 foreign key(A表中某字段) references B表(某主键字段);
- 添加主键:alter table 表名 add constraint 主键名字 primary key(某字段或某些字段);注意:某些字段指联合主键;
- 添加check约束:alter table 表名 add constraint 约束名 check (约束内容);eg:check(state=0 or state =1);
- 添加唯一性约束:alter table 表名 add constraint 约束名 unique (某字段);
- 创建视图:create view 视图名字 as 子查询。
常用
-
数据类型转换用:to_要转换的数据类型(某字段);
eg:to_char(name);to_date(‘2020-02-02’,‘时间格式’); -
若用到group by,则被查询的字段只能为group by 后面接的字段或者是函数(求和,平均,统计等),和mysql略有不同。当查询字段多余分组字段,可使用子查询解决。
-
链表查询有:普通连表查询,inner join,left join ,right join;其中left join已左表为主,right join 已右表为主;(为主的表中被查询字段将显示全部数据)。
-
主键自增实现方法(通过序列和触发器)。
步骤1:定义序列
create SEQUENCE 序列名
increment by 1
start with 1
nomaxvalue
minvalue 1
nocycle;
(解释 increment by 1:每次增量值为1, start with 1:增量开始值为1, nomaxvalue:增量无最大值, minvalue 1:最小开始值,nocycle:无缓存(缓存每次往后缓存一个值));步骤2:定义触发器
create or replace trigger 触发器名字
before insert on 表名
for each row
declare
leng int;
abc varchar2(10);
begin
select to_char(序列名.Nextval) into abc from dual;
leng:=5-length(abc);
select rpad(‘k’,leng,‘0’)||abc into:new.自增字段 from dual;
end;
插入数据时得到自增字段值为:k0001;
将触发器中最后换为: select lpad(abc,leng,‘0’) into:new.自增字段 from dual;得到结果为:0001。若不限制自增字段为几位数,则无需declare定义变量。 -
开窗函数(over())
用法eg:select avg(salary)over(partition by 字段1 order by 字段2)…
eg释义:对avg(salary)以字段1分组和以字段2排序。 -
分页查询(分页信息按照工资排序)
通过rownum实现:select * from (select rownum r,t.* from (select * from emp order by sal) t where rownum<=10 ) where r>5; -
nvl()函数
用法eg:nvl(to_char(birthday,‘yyyy-mm-dd’),‘日期不详’)
释义:当birthday存在时,将birthday以’yyyy-mm-dd’格式显示,不存在则显示:日期不详。 -
从一个日期中获取年月日用to_char()解决。
eg: select to_char(sysdate,‘yyyy’)from dual;:得到系统当前时间的年限。