MySQL的七种JOIN


建表

在这里我们先建立两张有外键关联的两张表:

    CREATE DATABASE db0206;
    USE db0206;
    CREATE TABLE `db0206`.`tbl_dept`(  
      `id` INT(11) NOT NULL AUTO_INCREMENT,
      `deptName` VARCHAR(30),
      `locAdd` VARCHAR(40),
      PRIMARY KEY (`id`)
    ) ENGINE=INNODB CHARSET=utf8;
    CREATE TABLE `db0206`.`tbl_emp`(  
      `id` INT(11) NOT NULL AUTO_INCREMENT,
      `name` VARCHAR(20),
      `deptId` INT(11),
      PRIMARY KEY (`id`),
      FOREIGN KEY (`deptId`) REFERENCES `db0206`.`tb_dept`(`id`)
    ) ENGINE=INNODB CHARSET=utf8;
    /*插入数据*/
    INSERT INTO tbl_dept(deptName,locAdd) VALUES('RD',11);
    INSERT INTO tbl_dept(deptName,locAdd) VALUES('HR',12);
    INSERT INTO tbl_dept(deptName,locAdd) VALUES('MK',13);
    INSERT INTO tbl_dept(deptName,locAdd) VALUES('MIS',14);
    INSERT INTO tbl_dept(deptName,locAdd) VALUES('FD',15);
    INSERT INTO tbl_emp(NAME,deptId) VALUES('z3',1);
    INSERT INTO tbl_emp(NAME,deptId) VALUES('z4',1);
    INSERT INTO tbl_emp(NAME,deptId) VALUES('z5',1);
    INSERT INTO tbl_emp(NAME,deptId) VALUES('w5',2);
    INSERT INTO tbl_emp(NAME,deptId) VALUES('w6',2);
    INSERT INTO tbl_emp(NAME,deptId) VALUES('s7',3);
    INSERT INTO tbl_emp(NAME,deptId) VALUES('s8',4);

Venn图与SQL语句的编写以及查询结果

  1. 内连接

内连接Venn图

图片.png

执行的SQL语句以及执行的查询结果:

  • 执行的SQL语句
    select * from tbl_dept a inner join tbl_emp b on a.id=b.deptId;
    
  • 查询结果
  1. 左外连接

执行的sql语句以及执行的查询结果:

  • 执行的sql语句
    select * from tbl_dept a left join tbl_emp b on a.id=b.deptId; 
    
  • 查询结果
  1. 右外连接

执行的sql语句以及执行的查询结果:

  • 执行的sql语句
    select * from tbl_dept a right join tbl_emp b on a.id=b.deptId 
    
  • 查询结果



Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • 2379. Minimum Recolors to Get K Consecutive Black Blocks
  • 2471. Minimum Number of Operations to Sort a Binary Tree by Level
  • 1387. Sort Integers by The Power Value
  • 2090. K Radius Subarray Averages
  • 2545. Sort the Students by Their Kth Score