参考文章:
https://www.jianshu.com/p/95c170ab5513
https://blog.csdn.net/weixin_39411321/article/details/90602030
MySQL除了普通的增删改查的sql 用的多以外,像多表查询其实在项目里用的是非常多的,下面就随着小编一起看下去吧
1) 知识体系
2)表
我这边准备了俩张表show_column 和user_coulmn ,show_column的id 和 user_column的 column_id 关联 ,user_column的uid 和bos_user的user_id 关联, 目前bos_user 这张表与下文演示无关。
3)内连接
显式内连接
主要原理是根据关联条件,从左表中查询每一条记录 去右表中的所有记录进行匹配,如果不满足关联条件,则数据查询不出来。
-- 1.显式内连接
-- 语法:select table1.*,table2.* from table1 inner join table2 on 关联条件
select a.* ,b.* from show_column a inner join user_column b on a.id= b.column_id where a.is_del='0';
隐式内连接
-- 2.隐式内连接
-- 语法: select table1.*,table2.* from table1,table2 where 关联条件
select a.*,b.* from show_column a,user_column b where a.id = b.column_id;
4)外连接
左外连接【left join】
以left 左边的表为主,查询出里面所有记录,根据关联条件查询右边表的数据,能匹配的正确保留,不能匹配的其他字段里面的值为null
-- 3.左外连接
-- 语法: select table1.*,table2.* from table1 a,
select a.page,a.field_name,a.id,b.* from show_column a left join user_column b on a.id = b.column_id
右外连接[right join]
原理: 查询出right 右边表的所有数据,根据关联条件查询 right 右边的数据,能够匹配的将数据查询出来,不能匹配的将数据设置为null.
-- 4.右外连接
select a.*,b.* from show_column a right join user_column b on a.id = b.column_id
5) 子查询
-- 5. 子查询
select a.* from show_column a where id in(select column_id from user_column );
6) 补充一个联合查询
union 关键字 ,union 代表查询俩张表去除重复后的数据,按照默认排序,union all 代表查询俩张表全部数据,且没有顺序