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`))
    

      

  • 相关阅读:
    PHP获取一周的日期
    关系型数据库和非关系型数据库的区别和特点
    关系型数据库和非关系型数据库的特性以及各自的优缺点
    什么是数据库?什么是关系数据库?什么是非关系型数据库?
    PHP中把对象转数组的几个方法
    验证银行卡号
    xss过滤方法
    PHP 随机字符
    计算两个日期相差年月日
    判断一个时间段是否包含周末
  • 原文地址:https://www.cnblogs.com/tianqizhi/p/9265892.html
Copyright © 2011-2022 走看看