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

吾爱主题 阅读:97 2024-04-02 08:04:13 评论:0

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

构建环境:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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 )

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

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

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

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

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

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

?
1 2 3 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 表独有)+

?
1 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表独有)

?
1 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 各自独有)

?
1 2 3 select * from t_emp e left join t_dept d on e.deptid= d.id where d.id is null union select * from t_emp e right join t_dept d on e.deptid= d.id where e.id is null ;

总结

本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注服务器之家的更多内容!

原文链接:https://blog.csdn.net/weixin_45821811/article/details/116074923

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容