二、SQL数据库的查询和操作
一、常用的类型
1、char(10):当数据小于10个字节时自动添加空格补齐
2、varchar2(10):数据小于10个字节时oralce自动判断识别数据的字节大小
3、number(4,2) :数据必须总长度是4位,小数点后没有也要占2位的数字(不包括小数点)
注意:小数点强制先占两位,再看整数位,小数点后超出范围四舍五入,整数不可以
4、date:储存日期和时间 如果添加日期没有时间自动补齐12:00:00
5、Timestamp:比date多了一个时区
二、创建表和约束
1、create table student
(
infos varchar2(7)not null, --学号
stuname varchar2(10)not null, --姓名
gender varchar2(2) not null, -- 性别
age number(2) not null, --年龄 number为整数不能有小数点
seat number(2) not null, --座号
enrolldate date, --入学时间
stuaddeess varchar2(50) default'地址不详', --住址
classno varchar2(4) not null --班号 =学期序号+班级序号
);
2、约束就是规定一个数据的值范围和值规则
3、添加约束:alter table 表名 add constraint 约束名 约束内容
-- 添加主键约束
alter table infos add constraint pk_infos primary key(stuid);
-- 添加列约束性别约束为男女
alter table infos add constraint ck_infos_gender check(gender in('男','女'));
-- 约束座号为0到50
alter table infos add constraint ck_infos_seat check(seat>=0 and seat<=50);
-- 约束年龄0到100
alter table infos add constraint ck_infos_age check(age between 0 and 100 );
-- 约束 班号
alter table infos add constraint ck_infodfss_classno check((classno between 1 and 1999) or (classno between 2000 and 2999));
--注意:如果数据中有数据 check时要注意取包括数据在内范围值
定义外键:alter table 表名 add constraints fk_emp_dept foreign key(列名) references 引用表名(列名);
注意:使用外键时,引用表数据必须包括添加外键的表数据
缓存区就是储存在内存条里还未写入数据库或者说硬盘的数据 commit;结尾可以将他写入进去
三、数据库操作语言
1、结果集做数据源:create table 表名 as select语句
2、to_date(‘字符串’,’格式’)将字符串转换日期格式:to_date(‘2009/8-9 6:7:8’;’yyyy/mm/dd hh24:mm:ss’);
3、truncate与delete类似 只是删除数据后无法通过日志恢复
4、select distinct 列名或者* from 表名;
5、判断是否为nul不能用 = 必须用is或者not,例如:select * from emp where ename is null;
6、in操作: where sal in(‘1000’,’2000’,’3000’);当等sal于in中值时就输出
7、between and 返回两个值之间范围包括两值:select *from emp where sal between 1000 and 2000;输出工资1000至2000的记录
8、通配符 s%:以S开头的字符串,_s%:第二个字符是S的字符串;
9、当要查询中出现带有%的数据时,使用通配符时就需要用到转义字符否则%当通配符读取: select * from studenta where name like '%30\%%'escape'\'; 查询name=30%的数据
四、集合运算
-- intersect交集(返回两个集合之间所有不相同的数据)
-- union all 并集 (返回查询的所有记录 包括重复)
-- union 并集 不包括重复值
-- minus 补集(返回两个集合不相同的值)
使用方法:求补运算
select deptno from dept
minus
select deptno from emp;
五、Union(并集) 插入多条数据
Insert into dept
Select语句
Union
Select语句
六、联接查询
1、内联接
Select e.列名,d.列名 from emp e,dept d where e.deptno=d.deptno;
Select e.列名,d.列名 from emp e inner join dept d on e.deptno=d.deptno;
2、外连接(通常联接没有外键的表):
Select e.列名,d.表名 from emp e left join dept d on e.deptno=d.deptno where sal=1000;
注意:外连接中有left和right left是以join左边的表做为主表联接 on联接条件 on联接完后会把主表中没有参加过联接的记录也显示出来
然后就where挑选数据