mysql数据库的常用操作-主键

  • 关于主键                                                                                

  • 外键一个特殊的索引,用于关键两个表,只能是指定的内容
  • 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`)
    ) 
     1 此时如果class 表中不存在id 1,student表也插入不了,这就叫外键约束
     2 mysql> insert into student2(id,name,class_id) values(1,'alex', 1);
     3 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`))
     4  
     5  
     6  
     7 mysql> insert into class(id,name) values(1,"linux");
     8 Query OK, 1 row affected (0.01 sec)
     9  
    10 mysql> insert into student2(id,name,class_id) values(1,'alex', 1);
    11 Query OK, 1 row affected (0.00 sec)
    12  
    13  
    14 #如果有student表中跟这个class表有关联的数据,你是不能删除class表中与其关联的纪录的
    15 mysql> delete from class where id =1;
    16 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`))

     

posted @ 2018-06-26 14:12  柒月不哭  阅读(161)  评论(0编辑  收藏  举报