MySQL 四种连接和多表查询详解

目录
  • mysql 内连接、左连接、右连接、外连接、多表查询
    • 一、inner jion 内连接 ( a ∩ b )
    • 二、left join 左外连接( a 全有 )
    • 三、right join 右外连接 (b 全有)
    • 四、full join 全外连接( a + b)
    • 五、left excluding join ( a – b 即 a 表独有)+
    • 六、right excluding join ( b – a 即 b表独有)
    • 七、outer excluding join (a 与 b 各自独有)

    mysql 内连接、左连接、右连接、外连接、多表查询

    构建环境:

    create table t_emp(
    	id int primary key, 
    	name varchar(20),
    	deptid int
    );
    create table t_dept(
    	id int primary key,
    	name varchar(20)
    );
    insert into t_dept(id, name) values(1, '设计部');
    insert into t_dept(id, name) values(2, '开发部');
    insert into t_dept(id, name) values(3, '测试部');
    insert into t_emp(id, name, deptid) values(1, '张三', 1);
    insert into t_emp(id, name, deptid) values(2, '李四', 2);
    insert into t_emp(id, name, deptid) values(3, '王五', 0);
    # ps:为了说明方便,t_emp 表 说成 a 表, t_dept 表说成 b 表

    目录

    一、inner jion 内连接 ( a ∩ b )

    select * from t_emp e inner join t_dept d on  e.deptid = d.id;

    二、left join 左外连接( a 全有 )

    select * from t_emp e left join t_dept d on e.deptid = d.id;

    三、right join 右外连接 (b 全有)

    select * from t_emp e right join t_dept d on e.deptid = d.id;

    四、full join 全外连接( a + b)

    select * from t_emp e left join t_dept d on e.deptid = d.id union select * from t_emp e right join t_dept d on e.deptid = d.id;

    五、left excluding join ( a – b 即 a 表独有)+

    select * from t_emp e left join t_dept d on e.deptid= d.id where d.id is null;

    六、right excluding join ( b – a 即 b表独有)

    select * from t_emp e right join t_dept d on e.deptid= d.id where e.id is null;

    七、outer excluding join (a 与 b 各自独有)

    select * from t_emp e left join t_dept d on e.deptid= d.id where d.id is nullunionselect * from t_emp e right join t_dept d on e.deptid= d.id where e.id is null;

    总结

    本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注www.887551.com的更多内容!

    (0)
    上一篇 2022年3月21日
    下一篇 2022年3月21日

    相关推荐