数据库MySQL-union(联合)

  • 2020 年 3 月 27 日
  • 笔记

1.8 union(联合)

插入测试数据

create table emp(         id tinyint unsigned auto_increment primary key,         name varchar(20) not null,         skill set('PHP','mysql','java')   );    insert into emp values (null,'李白',1),(null,'杜甫',2),(null,'白居易',4)  insert into emp values (null,'争青小子',3)

1.8.1 union的使用

作用:将多个select语句结果集纵向联合起来

语法:select 语句 union [选项] select 语句 union [选项] select 语句
-- 查询stu表中的姓名和emp表中姓名 结果自动合并的重复的记录  mysql> select stuname from stu union select name from emp;

例题:查询上海的男生和北京的女生

-- 方法一:  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可以将一个复杂的条件转成两个简单的条件

1.8.2 union的选项

union的选项有两个

1、 all:显示所有数据

2、 distinct:去除重复的数据【默认】

mysql> select stuname from stu union all select name from emp;

1.8.3 union的注意事项

1、 union两边的select语句的字段个数必须一致

2、 union两边的select语句的字段名可以不一致,最终按第一个select语句的字段名。

3、 union两边的select语句中的数据类型可以不一致。