zoukankan      html  css  js  c++  java
  • 外键

    外键,一个特殊的索引,用于关联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`))
    

      

  • 相关阅读:
    八大排序算法
    大数据系列文章汇总
    HBase原理、设计与优化实践
    hbase分页应用场景及分页思路与代码实现
    【HBase】zookeeper在HBase中的应用
    HBase什么时候作minor major compact
    Namenode HA原理详解(脑裂)
    【版本特性】sql server2005版本特性
    Navicat破解版下载安装
    MongoDB(2.2)MongoDB的安装与基本使用
  • 原文地址:https://www.cnblogs.com/tianqizhi/p/9265892.html
Copyright © 2011-2022 走看看