mysql教程:union(联合)

[复制链接]
查看2112 | 回复0 | 2020-10-12 21:32 | 显示全部楼层 |阅读模式
插入测试数据
代码如下:
  1. create table emp(
  2.        id tinyint unsigned auto_increment primary key,
  3.        name varchar(20) not null,
  4.        skill set('PHP','mysql','java')
  5. );

  6. insert into emp values (null,'李白',1),(null,'杜甫',2),(null,'白居易',4)
  7. insert into emp values (null,'争青小子',3)
复制代码
union的使用作用:将多个select语句结果集纵向联合起来
语法:
  1. select 语句 union [选项] select 语句 union [选项] select 语句
复制代码
  1. -- 查询stu表中的姓名和emp表中姓名 结果自动合并的重复的记录
  2. mysql> select stuname from stu union select name from emp;
复制代码
例题:查询上海的男生和北京的女生
  1. -- 方法一:
  2. mysql> select * from stu where (stuaddress='上海' and stusex='男') or (stuaddress='北京' and stusex='女');
  3. +--------+---------+--------+--------+---------+------------+------+------+
  4. | stuNo  | stuName | stuSex | stuAge | stuSeat | stuAddress | ch   | math |
  5. +--------+---------+--------+--------+---------+------------+------+------+
  6. | s25302 | 李文才       | 男       |     31 |       3 | 上海          |   77 |   76 |
  7. | s25303 | 李斯文       | 女      |     22 |       2 | 北京           |   55 |   82 |
  8. +--------+---------+--------+--------+---------+------------+------+------+
  9. 2 rows in set (0.00 sec)

  10. -- 方法二:union
  11. mysql> select * from stu where stuaddress='上海' and stusex='男' union select * from stu where stuaddress='北京' and stusex='女';
  12. +--------+---------+--------+--------+---------+------------+------+------+
  13. | stuNo  | stuName | stuSex | stuAge | stuSeat | stuAddress | ch   | math |
  14. +--------+---------+--------+--------+---------+------------+------+------+
  15. | s25302 | 李文才       | 男       |     31 |       3 | 上海          |   77 |   76 |
  16. | s25303 | 李斯文       | 女      |     22 |       2 | 北京           |   55 |   82 |
  17. +--------+---------+--------+--------+---------+------------+------+------+
  18. 2 rows in set (0.00 sec)

  19. 结论:union可以将一个复杂的条件转成两个简单的条件
复制代码
union的选项
union的选项有两个
1、     all:显示所有数据
2、     distinct:去除重复的数据【默认】
  1. mysql> select stuname from stu union all select name from emp;
复制代码
union的注意事项
1、     union两边的select语句的字段个数必须一致
2、     union两边的select语句的字段名可以不一致,最终按第一个select语句的字段名。
3、     union两边的select语句中的数据类型可以不一致。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

UID
1
贡献
387
丢币
38902
主题
4607
回帖
116
注册时间
2018-9-25
最后登录
2024-4-16