• 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;
    

  • 相关阅读:
    zabbix_agent 主动模式配置
    zabbix 监控ipmi
    超级详细全截图化VMware 安装ubantu
    docker 部署
    C# DataTable和List转换操作类
    C#类型转换工具类
    C# 注册windows 服务
    C# wsdl.exe 生成类文件
    visual studio code download url
    c# xml序列化和反序列化
  • 原文地址:https://www.cnblogs.com/chao460/p/14752811.html
Copyright © 2020-2023  润新知