MySQL链表查询(内连接,外连接-左外连接-右外连接,union

一. 内连接

获取的结果是两张表的交集
环境准备:
t_employee表: id为主键 t_depno为外键,连接t_dept的主键
在这里插入图片描述
t_dept表:id为主键
在这里插入图片描述

显示内连接

语法

#显式内连接
select * from 表A inner join 表B on 条件;
代码实现
#显式内连接
#没有使用别名
select * from t_employee 
inner join t_dept 
on t_employee.dept_no = t_dept.id;
#使用别名
select *
from t_employee t1
inner join t_dept t2 
on t1.dept_no = t2.id;

隐式内连接

语法
#隐式内连接
select * from 表A,表B where 条件;
代码实现
#隐式内连接
select * from t_employee t1 , t_dept t2 where t1.dept_no = t2.id;

总结:

  • 推荐使用显式内连接。

二. 外连接

概述:

  • 获取的结果是一张表的全部, 以及两张表的交集.
  • 左外连接就是看左边的表,右外连接就是看右边的表,而表的显示左边还是右边是根据你写的sql语句有关的.

左外连接

语法

左外连接
获取左边表(表A)的全部,以及两张表的交集.
也就左边表的全部显示,右边表要向左边补齐,没有的显示为空

select * from 表A left outer join 表B on 条件;

右外连接

语法

右外连接
就是向右边的表看起 A为左表 B为右表
获取右边表(表B)的全部,以及两张表的交集.,

select * from 表A right outer join 表B on 条件;

左外和右外的代码练习

获取所有部门, 以及每个部门中的员工

#左外连接
select * from t_dept left outer join t_employee on t_employee.dept_no = t_dept.id;

#右外连接
select * from t_employee right outer join t_dept on t_employee.dept_no = t_dept.id;

在代码的基础上家加深理解

  #左外连接
  SELECT * 
  FROM t_dept 
  LEFT OUTER JOIN t_employee
  #on  t_dept.id=t_employee.id;
  ON t_employee.id = t_dept.id
  
  #右外连接 
  #与上表就是左右区别,但是上边是已t_dept为基准,下面是已t_employee为基准的
  SELECT * 
  FROM t_dept 
  RIGHT OUTER JOIN t_employee
  #on  t_dept.id=t_employee.id;
  ON t_employee.id = t_dept.id
  
  SELECT * 
  FROM t_employee
  RIGHT OUTER JOIN t_dept 
  ON t_employee.id = t_dept.id;

在这里插入图片描述
在这里插入图片描述

三. union

概述

  • 合并两个select语句的结果集.

去重

语法
#获取select语句1和select语句2的并集, 并去重.
select语句1 union select语句2;

不去重

语法
#获取select语句1和select语句2的并集, 不去重.
select语句1 union all select语句2;

代码练习


#去重
select *
from t_employee
where id in (1, 2)
union 
select *
from t_employee
where id = 1 or id = 3;
//结构是就是  id = 1 ,2,3的数据
#不去重
select *
from t_employee
where id in (1, 2)
union all
select *
from t_employee
where id = 1 or id = 3;
//结果就是  id = 1,2, 1,3 的数据
``
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值