找回密码
 免费注册

mysql数据库教程union(联合)语法代码

[复制链接]
发表于 2022-11-27 21:18:17 | 显示全部楼层 |阅读模式
mysql数据库教程union(联合)语法代码

插入测试数据

  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语句结果集纵向联合起来

语法:select 语句 union [选项] select 语句 union [选项] select 语句

-- 查询stu表中的姓名和emp表中姓名 结果自动合并的重复的记录
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语句中的数据类型可以不一致。


QQ|Archiver|小黑屋|网站地图|深圳市金黑网络技术有限公司 ( 粤ICP备2021124338号|粤公网安备 44030702003689号 )

GMT+8, 2026-8-8 15:01 , Processed in 0.090013 second(s), 21 queries .

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表