一.外键作用
外键操作:为了给字段增加约束
二.创建外键的两种方式
- 建表时指定外键约束
create table 表名(
字段列表......,
[constraint 索引名] foreign key(本表的字段) references 外表(外表字段)
);
- 建表后修改
alter table 表名 add
[constraint 索引名] foreign key(本表的字段) references 外表(外表字段);
外表字段必须是主键
三.删除外键
alter table 表名 drop foreign key 索引名;
四.练习
1.有一张年级表
现在建一张学生表,要求对学生表的年级使用外键约束
create table student_test(
id int(11) auto_increment primary key,
name varchar(20),
gradeid int(11),
constraint akey foreign key(gradeid) references grade(gradeId)
);
现在往学生表插一些约束条件允许的学生数据,发现可以成功插入
mysql> insert into student_test (name,gradeid) values ('c',1),('d',3);
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> select * from student_test;
+----+------+---------+
| id | name | gradeid |
+----+------+---------+
| 1 | c | 1 |
| 2 | d | 3 |
+----+------+---------+
2 rows in set (0.00 sec)
现在插入年级表中没有的年级,这时候就未插入成功,因为年级受外键约束了,这就是外键的作用,你学废了吗?
mysql> insert into student_test (name,gradeid) values ('a',7);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test`.`student_test`, CONSTRAINT `akey` FOREIGN KEY (`gradeid`) REFERENCES `grade` (`gradeId`))
- 那如果想要往学生表中插入研三学生的数据应该怎么做呢?
answer:应该先在年级表中加入研三年级的数据,然后再在学生表中插入数据就可以了
- 那如果想要删掉年级表中的大一或者其他年级的数据可以删掉吗?
answer:不可以删掉,因为有引用所以不能删,应该先在学生表中先删掉大一或者其他年级的数据,然后再在年级表中删除数据就可以了
2.创建一张班级表
mysql> select * from class;
+----------+--------+
| cid | name |
+----------+--------+
| 1 | 小陈 |
| 2 | 小张 |
| 3 | 小何 |
+----------+--------+
3 rows in set (0.00 sec)
创建一张班级平均分表
mysql> select * from avg;
+------+-------+
| cid | avg |
+------+-------+
| 1 | 93.23 |
| 2 | 94.33 |
| 3 | 92.11 |
+------+-------+
3 rows in set (0.00 sec)
此时没有设置外键约束,现在想要把avg表的id字段设置外键约束应该怎么做呢?
alter table avg add constraint ckey foreign key(cid) references class (cid);
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0