zoukankan      html  css  js  c++  java
  • SQL语句(多表联查)

    +00.创建表结构

    0.1 学生表&上课记录

    #1、student表
    create table student(
    id int auto_increment,
    name char(32) not null,
    age int not null,
    register_data date not null,
    primary key (id)) 
    engine=InnoDB;
    
    
    #2、student_record表
    create table study_record (
      id int(11) auto_increment,
      day int NOT NULL,
      status char(32) NOT NULL,
      stu_id int(11) NOT NULL,
      primary key (id),
      CONSTRAINT fk_student_key FOREIGN KEY (stu_id) REFERENCES student (id)
    )
    engine=InnoDB;
    

    0.2 在student表中创建记录

    • 在student表中创建两条记录
    mysql> insert into student(name,age,register_data) values("zhangsan",100,"2016-06-20");
    mysql> insert into student(name,age,register_data) values("lisi",101,"2016-06-21");
    

    0.3 student_record表添加关联

    • 在student_record表中创建与student表的关联记录(day,status,stu_id)
    mysql> insert into study_record (day,status,stu_id) values(1,"yes",1);      # student表id=1第一天到了
    mysql> insert into study_record (day,status,stu_id) values(1,"yes",2);      # student表id=2第一天到了
    mysql> insert into study_record (day,status,stu_id) values(1,"yes",3);      # 会报错,因为student没id=3
    

    0.4 关联数据不能删除

    • 如果有student表中有student_record表关联的数据,你是不能删除student表中的记录(报错)
    mysql> delete from student where name='lisi';
    

    0.5 查看创建记录

    • 查看刚刚创建study_record表结构创建记录
    mysql> show create table study_record;
    

    01 left join(左连接)

    • 左连接:两个表的差集(左表有就显示)
    • 1、左连接where只影向右表,所以左表(student)中数据全部显示,右表study_record表中不符合where条件的数据不会显示
    mysql> select name,day,status from student left join study_record on student.id=study_record.stu_id;
    

    02.right join(右连接)

    • 右连接:两个表的差集(右表有才显示)

    • 1、右连接where只影向左表,所以左表(student)中不符合where条件的数据不会显示,右表study_record表内容全部显示

    • select * from student   right join    study_record  on  student.id=study_record.stu_id;
      

    03.inner join(内连接)

    • 内连接:两个表的交集

    • inner join:理解为“有效连接”,两张表中都有的数据才会显示left join

    select * from student  inner join  study_record  on  student.id=study_record.stu_id;      # 等价于面这条语句
    select * from student,study_record where study_record.stu_id = student.id;
    

    04.full join(全连接)

    select * from a FULL JOIN b on a.a = b.b;  
    # MySQL不支持这个命令(可以使用下面语句代替,两行是一个语句)
    select * from student left join study_record on student.id=study_record.stu_id 
    UNION
    select * from student right join study_record on student.id=study_record.stu_id;
    

  • 相关阅读:
    DW吃瓜课程——机器学习理论知识笔记(四)
    DW吃瓜课程——机器学习理论知识笔记(三)
    DW吃瓜课程——机器学习理论知识笔记(二)
    DW吃瓜课程——机器学习理论知识笔记(一)
    DataWhale编程实践——区块链学习笔记
    CV入门系列笔记——全球人工智能技术创新大赛【热身赛】CV异常检测赛道
    强化学习入门笔记系列——DDPG算法
    强化学习入门笔记系列——稀疏奖赏和模仿学习
    强化学习入门笔记系列——DQN算法
    Java_SPI思想
  • 原文地址:https://www.cnblogs.com/chao460/p/14752811.html
Copyright © 2011-2022 走看看