外键

外键,一个特殊的索引,用于关联2个表,只能是指定内容

mysql> create table class(
    -> id  int not null primary key,
    -> name char(16));
Query OK, 0 rows affected (0.02 sec)
 
 
CREATE TABLE `student2` (
  `id` int(11) NOT NULL,
  `name` char(16) NOT NULL,
  `class_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_class_key` (`class_id`),
  CONSTRAINT `fk_class_key` FOREIGN KEY (`class_id`) REFERENCES `class` (`id`)
);
#引号可以都不写。
create table student2(
    id int(11) not null,
    name char(16) not null,
    class_id int(11) not null,
    primary key (id),
    key fk_class_key (class_id),
    constraint fk_class_key foreign key (class_id) references class (id)
);
#default后边加char类型的,则需要加引号,int类型不需要加引号。如name char(16) NOT NULL default 'qi';id int not null default 0;

  

此时如果class 表中不存在id 1,student表也插入不了,这就叫外键约束
mysql> insert into student2(id,name,class_id) values(1,'alex', 1);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`testdb`.`student2`, CONSTRAINT `fk_class_key` FOREIGN KEY (`class_id`) REFERENCES `class` (`id`))
 
 
 
mysql> insert into class(id,name) values(1,"linux");
Query OK, 1 row affected (0.01 sec)
 
mysql> insert into student2(id,name,class_id) values(1,'alex', 1);
Query OK, 1 row affected (0.00 sec)
 
 
#如果有student表中跟这个class表有关联的数据,你是不能删除class表中与其关联的纪录的
mysql> delete from class where id =1;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`testdb`.`student2`, CONSTRAINT `fk_class_key` FOREIGN KEY (`class_id`) REFERENCES `class` (`id`))

  

原文地址:https://www.cnblogs.com/tianqizhi/p/9265892.html