zoukankan      html  css  js  c++  java
  • mysql外键关联

    主键:是唯一标识一条记录,不能有重复的,不允许为空,用来保证数据完整性

    外键:是另一表的主键, 外键可以有重复的, 可以是空值,用来和其他表建立联系用的。所以说,如果谈到了外键,一定是至少涉及到两张表。

    创建外键的方式:

    方式一:表已经创建好了,继续修改表的结构来添加外键,代码如下:

    create table student(
                id int primary key auto_increment,
                name char(32) not null,
                sex char(32)
    ); 

    create table class( id int primary key auto_increment, name char(32) not null, age int, dept_id int
    );

    在上述的俩个已经创建好的表中,添加外键:

    alter table class add foreign key(dept_id) references student(id)

    alter table class:在从表class中进行操作;

    add foreign key (dept_id):将从表的字段dept_id添加为外键;

    references student(id):映射到主表studentt当中为id的字段

    方式一:在创建表的时候增加外键,代码如下create table student(

                id int primary key auto_increment,
                name char(32) not null,
                sex char(32)
    ); 

    create table class( id int primary key auto_increment, name char(32) not null, age int, dept_id int
           constraint FK_id foreign key(dept_id) references student(id) );

    格式:[CONSTRAINT symbol] FOREIGN KEY [id] (从表的字段1) REFERENCES tbl_name (主表的字段2)
     

    CONSTRAINT symbol:可以给这个外键约束起一个名字,有了名字,以后找到它就很方便了。如果不加此参数的话,系统会自动分配一个名字。

    FOREIGN KEY:将从表中的字段1作为外键的字段。

    REFERENCES:映射到主表的字段2。

    
    

    删除外键:

    alter table student drop foreign key 外键名;
  • 相关阅读:
    The formatter threw an exception while trying to deserialize the message in WCF
    通过Web Deploy方式部署WCF
    The Managed Metadata Service or Connection is currently not available
    How to create Managed Metadata Column
    冒泡算法
    asp.net core 实战项目(一)——ef core的使用
    Vue学习笔记入门篇——安装及常用指令介绍
    Vue学习笔记入门篇——数据及DOM
    Vue学习笔记目录
    Chart.js在Laravel项目中的应用
  • 原文地址:https://www.cnblogs.com/ConnorShip/p/9808947.html
Copyright © 2011-2022 走看看