1. 建立数据库
备注:
1) oracle 不同于mysql 可以直接create database
2) oracle 创建schema时对应一个用户,即该schema的访问用户,与用户一一对应;但可以存在多个访问用户(带权限控制)
1.1 创建数据库文件CREATE TABLESPACE XX LOGGING DATAFILE 'D:\app\XX\oradata\orcl\XX.dbf' SIZE 1000M;
create temporary tablespace XX tempfile 'D:\app\XX\oradata\orcl\XX.dbf' size 1000m;
1.2 创建用户
CREATE USER XX IDENTIFIED BY XX DEFAULT TABLESPACE XX TEMPORARY TABLESPACE XX;
1.3 授权
grant connect, resource to XX;
grant create session to XX;
2. 数据库操作(默认sccot用户):
2.1 createcreate table persons(
person_id NUMBER PRIMARY KEY, first_name VARCHAR2(50) NOT NULL, last_name VARCHAR2(50) NOT NULL, score NUMBER, type VARCHAR2(20) );备注:
1) ORA-02000: missing ALWAYS keyword : 在11g版本里不用用GENERATED BY DEFAULT AS IDENTITY ,要用PRIMARY KEY
2) oracle 本来只有number类型,用作number(19,2),即有小数位;后为了兼容其他数据库,新增int,只能是整形2.2 insert
insert into persons values(1, 'fred', 'xu', 0, 'a');
insert into persons values(SEQ_PERSON_ID.NEXTVAL, 'fred3', 'xu3', 0, 'b')
备注:
1)oracle下设置自增没有mysql那么简单,步骤如下:
1.1) CREATE SEQUENCE SEQ_PERSON_ID start with 100; #创建一个序列
1.2) INSERT INTO persons VALUES(SEQ_PERSON_ID.NEXTVAL, 'fred1', 'xu1', 0, 'a');#此时插入persons表记录的person_id被设置成了100
1.3)也可以采用触发器的形式
CREATE TRIGGER persons_trigger BEFORE INSERT ON persons FOR EACH ROW WHEN (new.person_id is null) begin select SEQ_PERSON_ID.nextval into :new.person_id from sys.dual; end;备注:sys.dual 是个虚拟表,oracle保证里面只有一条记录
:new— 触发器执行过程中触发表作操作的当前行的新纪录 :old— 触发器执行过程中触发表作操作的当前行的旧纪录在有触发器之后,插入数据时不需要填写主键 INSERT INTO persons(first_name, last_name, score, person_type) VALUES('fred2', 'xu2', 0, 'a');
2.3 select
select * from persons where first_name = 'fred' or last_name = 'xu1'
select * from persons where first_name like '%fred%' select * from persons where CONCAT(first_name, last_name) like '%1%'select * from users where rownum BETWEEN 0 AND 5 #利用rownum关键字分页
2.4 group by
select AVG(score), person_type from persons group by person_type
select AVG(score), person_type from persons group by person_type having person_type = 'b'备注:
1)ORA-00979: not a GROUP BY expression group by 后的列要能被处理
2.5 in
select * from persons where person_type in ('a','b');
2.6 insert all
insert all
into persons(first_name, last_name, score, person_type) values('test', 'test', 1, 'c') into persons(first_name, last_name, score, person_type) values('test1', 'test1', 1, 'c1') into persons(first_name, last_name, score, person_type) values('test2', 'test2', 1, 'c2')SELECT 1 FROM dual;
备注:
SELECT 1 FROM dual; 最后一次select必须有
2.7 视图create view person_view as select * from persons where first_name like '%f%'
select * from person_view;
备注:
视图是需表,只是逻辑定义;除非是一种物化视图,那个才是有物理占用
2.8 索引
create index person_index on persons (first_name);