预备知识:
1、用户的创建与删除
create user testuser identified by d123; --创建用户testuser,密码为d123
grant connect ,resource to testuser; --授予testuser 用户 connect、resource 权限
2、定义基本表的基本语法
create table <表名>(<列名><数据类型>[<列级完整性约束条件>]
[,<列名><数据类型>[<列级完整性约束条件>]]...
[,<表级完整性约束条件>]);
--创建department表:
create table department(
dno varchar2(10) primary key,
tno varchar2(20),
dname nvarchar2(20) not null
);
关键字primary key 表示 dno 为 主码(唯一且不能为空);关键字not null 表示 dname 不能为空,tno 后面不带 not null,表示 tno 列的值可以为空。
3、修改基本表的基本语法
alter table <表名>[add <新列名><数据类型>[<完整性约束>]
[drop<完整性约束条名>]
[modify<新列名><数据类型>];--在oracle中修改表列采用关键字modify
(1)修改department表,添加deptdate列,表示系的成立时间;
alter table department add deptdate date;
(2)修改department表,把dname列的类型改为varchar2(40);
alter table department modify dname varchar2(40);
(3)修改department表,删除deptdate列;
alter table department drop column deptdate;
(4)修改department表,tno引用teacher表的主码tno;
alter table department add foreign key(tno) references teacher(tno);--在oracle中,外码必须使用括号括起来
4、删除基本表语法
drop table <表名>[restrict|cascade]
--删除名称为 test 的表
drop table test;
5、视图的创建语法
create view <视图名> [ (<列名> [,<列名>]...) ]
as <子查询> [with check option];
(1) 创建一个包含教工号、姓名、工资的视图,名为st;
create view st as select tno,tname,tsalary from teacher;
(2)创建一个包含“编号为 d001 的系的所有教师信息”视图,名为 us ,通过视图us更新教师信息时,必须保证教师所在系为 d001 ;
create view us as select * from teacher where dno = 'd001' with check option;
6、删除视图语法
drop view <视图名> [cascade]
--删除视图us
drop view us;
7、查询语句的基本语法
select [all | distinct] <目标列表达式> [ ,<目标列表达式> ] ... --6
from <表名或视图名> [ , <表名或视图名> ] ... --1
[where <条件表达式>] --2
[group by <列名>] --3 4
[having <条件表达式>] --5
[order by <列名2> [asc | desc] ]; --7
标准的select语句的解析顺序为:
(1)from 子句,对表、视图等进行笛卡儿积计算,假设结果记为V1;
(2)where 子句,基于指定的条件对V1进行筛选,假设结果为V2;
(3)group by 子句,将V2划分为多个分组;
(4)使用聚集函数进行计算,假设结果为V3;
(5)使用 having 子句对V3筛选分组,假设结果为V4;
(6)计算所有的表达式,假设结果为V5;
(7)使用 order by 对结果集V5进行排序。
--(1)查询学生表的详细信息
select * from student;
--(2)查询 Student 表中的年龄在20 到 24 之间的学生信息
select * from student where sage between 20 and 24;
8、commit 和 rollback
在oracle中,对基本表数据的更新操作必须使用 commit 进行提交或采用 rollback 进行撤销。