zoukankan      html  css  js  c++  java
  • MYSQL的一些概念

    外键

    在设计关系表时,如果有些数据冗余的,那么就可以考虑外键。比如一张记录学生信息的表,每行表示一个学生,记录了学生自己的信息,以及其所在学院的信息,比如学院名、学院的位置、学院老师数量等等。这里可能存在多个学生是同一个学院的,那么学院的信息就会冗余。此时应该将学院的信息抽出来独立成一张表,并在学生信息表中增加一列来记录学院信息表中对应的学院,此时就不会有冗余的情况了。

    外键可以将两张表关联起来,形成多对一的关系,是指学生信息表中的多行(即多个学生),是指学院信息表中的一行(即一个学院)。

    先给agent表的sellerid列添加一个外键指向seller表的sellerid列:

    alter table agent add constraint sellerid foreign key(sellerid) references seller(sellerid);
    

    下面试试插入一些数据,可以看到如果seller表为空的话,是没办法在agent表中新增一行带有sellerid的记录的,必须seller表中存在这个sellerid才可以新增记录成功。不过注意到agent表中的sellerid列是允许为NULL的,那么随意新增一个不带sellerid的记录也是允许。

    mysql> insert into agent(agentid, sellerid) values(2, 3);
    ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`user`.`agent`, CONSTRAINT `sellerid` FOREIGN KEY (`sellerid`) REFERENCES `seller` (`sellerid`))
    mysql> 
    mysql> insert into seller(sellerid) values(3);
    Query OK, 1 row affected (0.04 sec)
    
    mysql> insert into agent(agentid, sellerid) values(2, 3);
    Query OK, 1 row affected (0.12 sec)
    
  • 相关阅读:
    设计模式
    设计模式
    设计模式
    设计模式
    【Sublime】许可证 及 相关设置
    【Linux】跳过ubuntu grub2引导,使用Windows引导ubuntu
    【Linux】Windows 7下硬盘安装Ubuntu 14.10图文教程
    【ACM】连连看 hdu1175
    【算法】约瑟夫环 C++源代码
    【Java】配置JAVA的环境变量
  • 原文地址:https://www.cnblogs.com/xcw0754/p/13834433.html
Copyright © 2011-2022 走看看