• MySQL数据库之union联合查询


    联合查询(union)

    MariaDB [sel]> create table resume(
        -> id tinyint unsigned auto_increment primary key,
        -> name varchar(20) not null,
        -> skill set('php','mysql','javascript')
        -> );
    # `Query OK, 0 rows affected (0.023 sec)`
    
    MariaDB [sel]> insert into resume values (null,'Kimmy',1),(null,'Jerry',3);
    # `Query OK, 2 rows affected (0.009 sec)`
    # `Records: 2  Duplicates: 0  Warnings: 0`
    

    union的使用

    • 作用

      • 将多个select语句结果集纵向联合起来
      • union可以将一个复杂的条件转成两个简单的条件
    • 语法

      • select 语句 union [选项] select 语句 union [选项] select 语句
    MariaDB [sel]> select name from grades union select name from resume;
    +-------+
    | name  |
    +-------+
    | Sunny |
    | Jerry |
    | Marry |
    | Tommy |
    | Kimmy |
    +-------+
    # `5 rows in set (0.008 sec)`
    
    -- 方法一:where
    mysql> select * from stu where (stuaddress='上海' and stusex='男') or (stuaddress='北京' and stusex='女');
    +--------+---------+--------+--------+---------+------------+------+------+
    | stuNo  | stuName | stuSex | stuAge | stuSeat | stuAddress | ch   | math |
    +--------+---------+--------+--------+---------+------------+------+------+
    | s25302 | 李文才   | 男     |    31 |       3 | 上海        |   77 |   76 |
    | s25303 | 李斯文   | 女     |    22 |       2 | 北京        |   55 |   82 |
    +--------+---------+--------+--------+---------+------------+------+------+
    # `2 rows in set (0.00 sec)`
    
    -- 方法二:union
    mysql> select * from stu where stuaddress='上海' and stusex='男' union select * from stu where stuaddress='北京' and stusex='女';
    +--------+---------+--------+--------+---------+------------+------+------+
    | stuNo  | stuName | stuSex | stuAge | stuSeat | stuAddress | ch   | math |
    +--------+---------+--------+--------+---------+------------+------+------+
    | s25302 | 李文才  | 男      |     31 |       3 | 上海       |   77 |   76 |
    | s25303 | 李斯文  | 女      |     22 |       2 | 北京       |   55 |   82 |
    +--------+---------+--------+--------+---------+------------+------+------+
    # `2 rows in set (0.00 sec)`
    

    union的选项

    • union的选项有两个
      • all 显示所有数据
      • distinct 去除重复的数据[默认]
    MariaDB [sel]> select name from grades union all select name from resume;
    +-------+
    | name  |
    +-------+
    | Sunny |
    | Jerry |
    | Marry |
    | Tommy |
    | Sunny |
    | Kimmy |
    | Jerry |
    +-------+
    # `7 rows in set (0.001 sec)`
    

    union的注意事项

    • union两边的select语句的字段个数必须一致
    • union两边的select语句的字段名可以不一致,最终按第一个select语句的字段名
    • union两边的select语句中的数据类型可以不一致
  • 相关阅读:
    RAID磁盘阵列
    Activiti任务认领
    Activiti 5.18启动流程到完成所有任务之间的数据库变化(转)
    tomcat优化(转)
    DB2 OLAP函数的使用
    PreparedStatement批量处理和事务
    获取JavaScript异步函数的返回值
    DB2 sql报错后查证原因与解决问题的方法
    DB2有五种约束
    连接db2数据库出现No buffer space available (maximum connections reached?)
  • 原文地址:https://www.cnblogs.com/SharkJiao/p/14137803.html
Copyright © 2020-2023  润新知