一.数据完整性约束
、约束
1主键约束 primary key
create table table2
(pid char(6) primary key,
pname char(10));
creat table orderdetail
(cutomerid char(6),
productid char(6),
quantity int,
primary key c_p_index(customerid,productid))
如果表格已经存在,可以通过修改表格的语句来添加主键
create table table3
(id int,name char(6));
alter table table3
add constraint primary key(id);
2.唯一性约束
create table table4
(num char(6),name varchar(10))
当插入数据或者更新数据时,如果和原来的值一样,这时禁止完成插入或更新
create table table4
(num char(6),
name varchar(6),
unique key(name)
);
create table table4
(num char(6),name varchar(10));
alter table table4
add constraint [约束名字] unique key(name);
alter table table4
drop primary key;
3参照的完整性约束
xs 学号(pk)
xs_kc:学号(fk)
alter table xs_kc
add [constraint xh_constraint] foregin key(学号)//指明那一列为外键
references xs(学号);
on delete restrict
restrict:当xs中的某一条记录删除,得看这个学生是否有选课的记录,如果该学生有选课记录,禁止这次删除的操作。
delete from xs where 学号=‘091107’;禁止的,是因为091107学生在xskc中有选课记录
二.1.多表连接查询
(1)全连接
select 列名1,列名2。。
from 表名1,表名2,。。
select xs 学号,姓名,课程号,成绩
from xs,xskc
where xs.学号=xskc.学号;
select 学号,课程号.课程名.学时
from xskc ,kc
where xskc.课程号=kc,课程号;
(2)标准sql语句
1)内链接:多个表通过连接条件中共享列的值进行的比较连接 from 表名1[inner] join 表名2 on 连接条件
select 列表名
from 表名1 join列表名2
on 连接条件
select xs.学号,姓名,课程号,成绩
from xs join xskc
on xs.学号=xskc.学号;
select姓名,课程,成绩
from xs join xskc on xs.学号=xskc.学号
join kc on xskc.课程号=kc.课程号;
select xs.学号,姓名,课程号,成绩
from xs join xskc
using(学号);
2)外连接:包含来自一张表的所有记录行和另一张的匹配记录行
左外连接:左边表格(join关键字 左边的)全部显示
右外连接:
查询:所有学生的学号,姓名以及他们所选的课程的课程号,得分
select xs.学号,姓名,课程号,成绩
from xs left outer join xskc
on xs.学号=xskc.学号;
查询学生选修课程的信息(学号。课程号。课程名),还看没有被学生选修的课程的情况
select 学号,xskc,课程号,课程名
from xskc right outer join kc
on xskc.课程号=kc.课程号;
3)自然连接
natural join 自然连接
natural left join
natural right join
select xs.学号,姓名,课程号,成绩
from xs natural join xskc;
4)交叉连接 -笛卡尔积
select xs.学号,姓名,课程号,成绩
from xs cross join xskc;