AI编程助手
AI免费问答

MySQL中union和unionall区别是什么

PHPz   2023-05-30 08:04   2072浏览 转载

union:对多个结果集进行并集操作,不包括重复行,同时进行排序。

union all:对多个结果集进行并集操作,包括重复行,不进行排序。

查询部门小于30号的员工信息,和部门大于20小于40号的员工信息。

①.先查询部门小于30号的员工信息。

   SELECT 
               employees_id
               ,last_name
               ,salary
               ,department_id
     FROM      employees
    WHERE      department_id <p><img src="https://img.php.cn/upload/article/000/000/164/168540505254224.png?x-oss-process=image/resize,p_40" alt="MySQL中union和unionall区别是什么"></p><p>查询部门大于20小于40的员工信息。</p><pre class="brush:sql;">   SELECT 
           employees_id
           ,last_name
           ,salary
           ,department_id
     FROM  
           employees
    WHERE 
           department_id BETWEEN 20 and 40;```

MySQL中union和unionall区别是什么

③.用union连接两张表

    SELECT 
            employees_id
            ,last_name
            ,salary
            ,department_id
      FROM  
            employees
     WHERE  
            department_id <p>其结果默认排序并去重,两张表都有30号部门信息,结果只出现一次。</p><p><img src="https://img.php.cn/upload/article/000/000/164/168540505210591.png?x-oss-process=image/resize,p_40" alt="MySQL中union和unionall区别是什么"></p><p>④.下面用union all连接两张表</p><pre class="brush:sql;">     SELECT 
              employees_id                 
              ,last_name                 
              ,salary                  
              ,department_id     
       FROM  
              employees  
      WHERE  
              department_id <p>其结果没有去重,也没有排序,排序结果对比下边结果,先去查询20到40的员工信息,在查小于30的员工信息。</p><p><img src="https://img.php.cn/upload/article/000/000/164/168540505240341.png?x-oss-process=image/resize,p_40" alt="MySQL中union和unionall区别是什么"></p><p>⑤.对比查询结果</p><pre class="brush:sql;">     SELECT 
             employees_id
             ,last_name
             ,salary
             ,department_id
       FROM  
             employees
      WHERE  
             department_id BETWEEN 20 and 40
  UNION ALL
     SELECT 
             employees_id
             ,last_name
             ,salary
             ,department_id
       FROM  employees
      WHERE  department_id <p><img src="https://img.php.cn/upload/article/000/000/164/168540505388040.png?x-oss-process=image/resize,p_40" alt="MySQL中union和unionall区别是什么"></p><p>默认是没有进行排序的。</p>
声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除