外键中,当主表的记录被子表参照时,主表记录不允许被删除。 解决方案: 先删除字表数据,在删除父表数据。 先将字表关联数据设为null,在删除父表数据 先将子表数据修改,在删除父表数据。 on delete cascade 当删除父表数据时,级联删除子表数据。 on set null 当删除父表数据时,将关联的数据设置为null
表级约束: create table tb_student( id int, name varchar2(18), sex char(3), age int, phone varchar2(18), email varchar2(18), address varchar2(18), clazz_id int, constraints tb_students_pk primary key(id), check(name is not null), check(sex=男 or sex=女), check(age>18 and age<50), unique(phone), unique(email), constraints tb_students_fk foregin key(clazz_id) reference tb_clazz(id) ); 自定义约束名:(约束 约束名 约束类型) constraints tb_students_pk 建议建表: 外键以表级约束,其他用列级约束。 约束的维护(添加、删除): alter table tb_student add primary key(id); 删除约束根据约束名删除: alter table tb_student drop constraints tb_students_pk; 复合约束(只能在表级中定义): primary key(year,month) (5)nvl函数 nvl(第一个参数,第二个参数), 如果第一个参数为null,则取第二个参数 定义字段的别名as select empno as eID,ename,sal,sal*12 as yearsal from scott.emp; distinct关键字去除重复数据: select distinct deptno from scott.emp; 比较运算符: select *from scott.emp where sal>=800 and sal<=1600; select * from scott.emp where sal between 800 and 1600; select * from scott.emp where deptno=20 or deptno=30; select * from scott.emp where deptno in(20,30); 模糊查询like: %匹配所有 _匹配一个字符 select * from scott.emp where ename like s%; select * from scott.emp where ename like %s; select * from scott.emp where ename like %s%; select * from scott.emp where ename like _s%; 优先级规则:先and后or 对结果排序 order by asc(升序 默认) desc(降序) select * from scott.emp order by sal asc; select * from scott.emp order by sal desc; (6)多表连接 内连接(等值连接) 两个表(或连接)中某一数据项相等的连接称为内连接。 SELECT FROM dept d INNER JOIN emp e ON d.deptno = e.deptno; 外连接(非等值连接) 用于查询一张表在另一张表中没有关联数据的信息 外连接分为三种: 左外连接(LEFT OUTER JOIN) 右外连接(RIGHT OUTER JOIN) 全外连接(FULL OUTER JOIN) -- 左外连接:+号在右边,左边的表的所有数据都要显示,如果右边表没有对应的数据,则补Null -- 右外连接:+号在左边,右边的表的所有数据都要显示,如果左边表没有对应的数据,则补Null -- 全外连接:两张表的所有数据都要全部显示 备份一张表(只备份数据,不备份约束): create table tb_emp as select * from scott.emp; select e.empno,e.ename,e.mgr,t.ename from scott.emp e,tb_emp t where e.mgr=t.empno and e.empno=7369; 自连接: select e.empno,e.ename,e.mgr,t.ename from scott.emp e,scott.emp t where e.mgr=t.empno and e.empno=7369; (7)组函数:(组函数都会忽略NULL值) 对一组值进行运算,并返回单个值,也叫聚合函数。 count(*|列名) 统计行数: select count(*) from scott.emp; select count(comm) from scott.emp; sum(数值类型列名) 求和: select sum(sal) from scott.emp; avg(数值类型列名) 平均值: select avg(sal) from scott.emp; max(列名) 最大值: select max(sal) from scott.emp; min(列名) 最小值: select min(sal) from scott.emp; (8)分组 group by 把该列具有相同值得多条记录当成一条记录处理,最后只输出一条记录。 分组函数忽略空值。结果集隐式按升序排列, 如果需要改变排序方式可以使用order by子句。 按部门分组: select deptno from scott.emp group by deptnot; 按工作岗位分组: select job from scott.emp group by job; group by子句的真正作用在于与各种组函数配合使用: select deptno,count(*),sum(sal),avg(sal),max(sal),min(sal) from scott.emp group by deptno;
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-73999-3.html
中华士魄
人家的确是在公海航行
他要的就是你这句话