zoukankan      html  css  js  c++  java
  • 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
    );
     
     
     
     
  • 相关阅读:
    crawlspider的源码学习
    df 参数说明
    Linux top 命令各参数详解
    Redis info参数总结
    python 读写 Excel文件
    python之Selenium库的使用
    heapq模块
    Python数据库连接池DButils
    【leetcode】701. Insert into a Binary Search Tree
    【leetcode】940. Distinct Subsequences II
  • 原文地址:https://www.cnblogs.com/hebao0514/p/4885757.html
Copyright © 2011-2022 走看看