zoukankan      html  css  js  c++  java
  • 程序媛计划——mysql外键

    定义

    外键:如果一个表的某个字段指向另一个表的主键,就称之为外键。被指向的表,称之为主表,也叫父表,那么另一个表就是从表,也叫子表

    #先新建两个表

    mysql> create table author_table(
        -> author_id int(4) not null primary key auto_increment,
        -> author_name char(20) not null);
    Query OK, 0 rows affected (0.02 sec)
    mysql> create table article_table(
        -> article_id int(4) not null primary key auto_increment,
        -> article_title char(20) not null,
        -> author_id int(4) not null,
        -> foreign key(author_id) references author_table(author_id));  #这一步使得article_table中的author_id字段成为外键
    Query OK, 0 rows affected (0.02 sec)

    #添加数据

    mysql> insert into author_table values
        -> (1,'zhao'),
        -> (2,'qian'),
        -> (3,'sun'),
        -> (4,'li');
    Query OK, 4 rows affected (0.01 sec)
    Records: 4  Duplicates: 0  Warnings: 0
    mysql> insert into article_table values
        -> (1001,'c++',1),
        -> (1002,'java',1),
        -> (1003,'python',2),
        -> (1004,'mysql',3),
        -> (1005,'jacascript',4);
    Query OK, 5 rows affected (0.00 sec)
    Records: 5  Duplicates: 0  Warnings: 0

    #子表和附表之间的约束

    0 article_table中不能添加author_id为5的记录;

    1 author_table中不能删除author_id为4的记录,因为子表中还有作者4的文章

    #删除外键约束

    mysql> alter table article_table drop foreign key article_table_ibfk_1;
    Query OK, 0 rows affected (0.02 sec)
    Records: 0  Duplicates: 0  Warnings: 0

    #级联操作

    #添加外键

    mysql> alter table article_table
        -> add foreign key fk_id(author_id)  #这里fk_id可以自己指定
        -> references author_table(author_id)
        -> on delete cascade  #cascade表示关联操作。子表会依赖父表中的数据关联删除或更新
        -> on update cascade;    
    Query OK, 5 rows affected (0.02 sec)
    Records: 5  Duplicates: 0  Warnings: 0

    #set null关键字

    set null,表示子表数据不指向父表任何记录。当不加set null和cascade时,默认为restrict(拒绝主表的相关操作),所以开始主表无法删除数据

  • 相关阅读:
    Centos-获取远程主机对应端口信息-telnet
    Centos-跟踪数据传输路由状态-traceroute
    Centos-本机网络连接、运行端口和路由表等信息-netstat
    Centos-远程拷贝-scp
    Centos-配置网络或显示当前网络接口状态-ifconfig
    Centos-挂载和卸载分区-mount
    Centos-退出抽取设备-eject
    Centos-强制将内存中数据写入磁盘-sync
    Centos-检查文件系统并尝试修复-fsck
    数据结构-静态查找表
  • 原文地址:https://www.cnblogs.com/IcarusYu/p/7533482.html
Copyright © 2011-2022 走看看