MySQL(16):Select-union(联合查询)

1. Select-union(联合查询)

union用于把来自许多SELECT语句的结果组合到一个结果集合中。
用法:
SELECT ...UNION [ALL | DISTINCT]SELECT ...[UNION [ALL | DISTINCT]SELECT ...]
 
2. 引入Select-union(联合查询)的案例:
(1)首先查询出所有teacher_class列中所有的记录,如下:
 
 
 
(2)按照字段t_name和days,查询出所有带过php0115班的老师,如下:
 
 
(3)在上面(2)查询出来的结果基础上,按照days进行排序检索,如下:
 
 
 
(4)在(3)查询结果的基础上,检索出days最大的记录,如下:
 
 
(5)如果我们想查询出php0228班的授课天数(days最大)老师记录,就需要上面查询命令的班级号就行了,如下:
select t_name,days from teacher_class where c_name='php0228' order by days desc limit 1;
如此一来,如果数据库内容很多,我们可能要重复很多这样的业务逻辑,该怎么优化呢?
 
 
3. Select-union(联合查询)的案例:
Select-union(联合查询):把多条select语句的结果,合并在一起。
使用uinion关键字,联合两个select语句即可。
 
  现在说明我们的需求:获得2个班代课最后的老师。
 
语句1:select t_name,days from teacher_class where c_name='php0115' order by days desc limit 1;
语句2:select t_name,days from teacher_class where c_name='php0228' order by days desc limit 1;
使用union关键字联合上面两个select语句即可。
(1)语句1 和 语句2,查询结果如下:
 
 
(2)使用union关键字联合上面两个select语句,如下:
(select t_name,days from teacher_class where c_name='php0115' order by days desc limit 1)union( select t_name,days from teacher_class where c_name='php0228' order by days desc limit 1
);
 
 
 
 

转载于:https://www.cnblogs.com/hebao0514/p/4885757.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值