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语句中的数据类型可以不一致
posted @ 2020-12-15 12:15  wing1377  阅读(417)  评论(0编辑  收藏  举报