mysql 外键关联

什么是外键:
外键是一个特殊的索引,用于关联两个表,只能是指定内容。

如我将新建一个daka的表,然后将此表的class_id 与另外一个class的表的cid字段关联

class表:

CREATE TABLE `class` (
`cid` int(11) NOT NULL AUTO_INCREMENT,
`caption` varchar(32) NOT NULL,
PRIMARY KEY (`cid`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

mysql> select * from class;
+-----+------------+
| cid | caption |
+-----+------------+
| 1 | 高二1班 |
| 2 | 高二2班 |
| 3 | 高二3班 |
| 4 | 高二4班 |
| 5 | 高二5班 |
+-----+------------+

daka表:

CREATE TABLE `daka` (
`id` int(11) AUTO_INCREMENT NOT NULL,
`student_name` char(16) NOT NULL,
`state` ENUM("Y","N") NOT NULL,
`class_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fk_class_key` FOREIGN KEY (`class_id`) REFERENCES `class` (`cid`)
)

#fk_class_key 这个表示这个外键约束名称,自定义的,此时在

开始往daka表中插入数据,(此时在class_id字段中的值,就必须在class表中的cid字段中要存在如果不存在则会报错,被外键约束)

正常:
mysql> INSERT INTO `daka` (student_name,state,class_id) values("赵丽颖","Y","3");
Query OK, 1 row affected (0.04 sec)

报错:
mysql> INSERT INTO `daka` (student_name,state,class_id) values("赵丽颖","Y","6");
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`newtest`.`daka`, CONSTRAINT `fk_class_key` FOREIGN KEY (`class_id`) REFERENCES `class` (`cid`))

在删除的数据的过程中,如果是删除daka表中有外键约束的数据则没有问题,但是如果是删除class表中被外键关联的数据则就会报错,

如下:
mysql> select * from daka;
+----+--------------+-------+----------+
| id | student_name | state | class_id |
+----+--------------+-------+----------+
| 1 | 赵丽颖 | Y | 3 |
| 8 | 赵丽颖1 | Y | 5 |
+----+--------------+-------+----------+
2 rows in set (0.00 sec)

mysql> select * from class;
+-----+------------+
| cid | caption |
+-----+------------+
| 1 | 高二1班 |
| 2 | 高二2班 |
| 3 | 高二3班 |
| 4 | 高二4班 |
| 5 | 高二5班 |
+-----+------------+
5 rows in set (0.00 sec)

mysql> DELETE FROM daka WHERE id=8;
Query OK, 1 row affected (0.08 sec)

mysql> DELETE FROM class WHERE cid=3;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`newtest`.`daka`, CONSTRAINT `fk_class_key` FOREIGN KEY (`class_id`) REFERENCES `class` (`cid`))

此处cid=3的这行数据被外键关联了,daka表中有引用他,所以不能直接被删除。

05-06 17:45