zoukankan      html  css  js  c++  java
  • 外键的变种,单表和多表的查询

    一、因为 foreign key 的约束 使得两张表之间的关系有三种,既一对一、多对一、多对多

      1、一对一,通过给另一张表的外键设置unique 来约束

      2、多对一关系

     1 #创建一个班级表(主表)
     2         create table class (
     3             cid int primary key auto_increment,
     4             caption varchar(20) not null
     5         );
     6         
     7     # 创建一个学生表(从表)
     8         create table student(
     9             sid int primary key auto_increment,
    10             sname varchar(20) not null,
    11             gender enum("男",''),
    12             class_id int not null,
    13             
    14             #关联学生表
    15             constraint fk_class foreign key(class_id) references class(cid)
    16             on delete cascade #同步删除记录
    17             on update cascade #同步修改记录
    18         
    19             );

       3、多对多的关系

        多对多的两张表 需要找第三张表来关联

     1 #创建一个课程表
     2  create table course(
     3      cid int primary key auto_increment,
     4      cname varchar(20) not null,
     5      teacher_id int not null,
     6      constraint fk_teacher foreign key(teacher_id) references teacher(tid)
     7      on delete cascade
     8      on update cascade);
     9      
    10  #创建一个学生表
    11  create table student (
    12     sid int primary key auto_increment,
    13     sname varchar(20) not null,
    14     gender enum ('',''),
    15     class_id int not null
    16  
    17  );
    18      
    19  #创建一个成绩表来关联学生表和课程表
    20 create table score(
    21     sid int primary key  auto_increment,
    22     student_id int not null,
    23     course_id int not null,
    24     number int not null,
    25     constraint fk_student_id foreign key(student_id) references student(sid)
    26     on update cascade
    27     on delete cascade,
    28     constraint fk_course_di foreign key(course_id) references course(cid)
    29     on update cascade
    30     on delete cascade
    31 );

     二、单表查询

      查询条件:

      1、where:

        between   A  and  B , between in (a,b,c),like %(前后o个或多个字符)  __(前后只能有一个字符)

      2、order by:

      3、group by:

        1、按照某个相同的字段分组

        2、分组后查看组内的信息(聚合函数):

     1     
     2 #每个部门有多少员工
     3 select post,count(id) from employee group by post;
     4 
     5 # 每个部门的最高薪水
     6 select post,max(salary) from employee group by post;
     7 
     8 # 每个部门的最低薪水
     9 select post,min(salary) from employee group by post;
    10 
    11 # 每个部门的平均薪水
    12 select post,avg(salary) from employee group by post;
    13 
    14 # 每个部门的所有薪水
    15 select post,sum(salary) from employee group by post;

      4、Having:

      5、Limit:

  • 相关阅读:
    数字建模工具
    博客园文档保存为pdf适合手机kindle阅读
    单点登录sso规范
    office在线预览方案
    KVM 虚机怎么热添加disk
    linux-基础FTP 协议传输
    TCP 三次握手四次挥手
    autossh 实现反向代理实现通过外网访问内网环境
    keepalived的工作原理
    openstack-ovs命令记录
  • 原文地址:https://www.cnblogs.com/liaopeng123/p/9799018.html
Copyright © 2011-2022 走看看