时间:2021-07-01 10:21:17 帮助过:36人阅读
主键:primary key 可以指定一列或多列为主键,主键在表中的总是唯一的,且构成主键的一部分的列的不允许为空。 惟一性原则:表中不同的行在主键上有唯一的。有必要区分primary key和super key。 unique唯一键键 一个表只能有一个主键,但可以有多个唯一键。
主键:primary key一个表只能有一个主键,但可以有多个唯一键。唯一键可以为空值。
替代键:unique
一个表只能有一个主键,但可以有多个替代键。替代键可以为空值。
它可以是数据表内不作为主键的其他任何列。在替代键列内不允许出现数据重复的现象。
如果存储在表A中的数据也必须存在表B中,且两个表中的数据必须一致,这种类型关系称为参照完整新约束。
参照动作:定义外键时可以添加更新时的参照动作:当一个表执行一种动作时参照表也执行相应的动作。
参照动作有:uodata和delete⑤ NO ACTION(无动作,默认的)
check完整性约束例如:
这个表的主键是stu_id,其中stu_name不允许为空值,所有的行中stu_tel不能有重复,且所有学生的成绩stu_score必须大于60分。
- create table student(
- stu_id int not null primary key,
- stu_name varchar(5) not null,
- stu_tel int(5) unique,
- stu_score int(2) check (stu_score>=60)
- );
- create table student1(
- id
- int not null primary key,
- stu_address
- varchar(5),
- foreign key(id) references student(stu_id)
- on update cascade
- on delete restrict
- );
- mysql> select * from student;
- +--------+----------+---------+-----------+
- | stu_id | stu_name | stu_tel | stu_score |
- +--------+----------+---------+-----------+
- | 1 | a | 150 | 60 |
- +--------+----------+---------+-----------+
- 1 row in set (0.00 sec)
- mysql> select * from student1;
- +----+-------------+
- | id | stu_address |
- +----+-------------+
- | 1 | china |
- +----+-------------+
- 1 row in set (0.00 sec)
- mysql> update student set stu_id=3 where stu_id=1;
- Query OK, 1 row affected (0.09 sec)
- Rows matched: 1 Changed: 1 Warnings: 0
- mysql> select * from student;
- +--------+----------+---------+-----------+
- | stu_id | stu_name | stu_tel | stu_score |
- +--------+----------+---------+-----------+
- | 3 | a | 150 | 60 |
- +--------+----------+---------+-----------+
- 1 row in set (0.00 sec)
此时不能删除delete表student中stu_id=3的数据,因为参照动作on delete restrict;
- mysql> select * from student1;
- +----+-------------+
- | id | stu_address |
- +----+-------------+
- | 3 | china |
- +----+-------------+
- 1 row in set (0.00 sec)