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;
    

  • 相关阅读:
    随笔12 java反射机制
    随笔11 J2EE中常用的名词解释
    随笔⑩ java中的基本数据类型的基础知识
    随笔⑨ java中的变量 --- 类变量(静态变量),final变量,成员变量,局部变量 java中的方法 --- 类方法(静态方法),final方法,成员方法(实例方法),构造方法
    随笔⑧ java中的存根类 --- Stub
    随笔⑦ Java中的比较 ==,equals以及精度对比较的影响
    随笔⑥ 关于线程 --- 线程操作的主要方法
    Jupyter notebook and Octave kernel installation
    [C7] Andrew Ng
    [C6] Andrew Ng
  • 原文地址:https://www.cnblogs.com/chao460/p/14752811.html
Copyright © 2011-2022 走看看