MySql 高级查询 union 联合查询

1. union 联合查询
	将多个查询结果集合到一起

2. 语法
	select 查询语句
	union
	select 查询语句
	union
	select 查询语句
	union
	select 查询语句

3. 例子: 查询学生信息和班级信息,集合到一起
select class_id,class_name,class_room from class
UNION
select name,age,sex from student;

说明:
	1. 联合查询要求列的数量要一致
	2. 列名以第一个查询结果为准

4. 例子: 查询男同学,要求年龄降序排列, 女同学要求年龄升序排列, 集合一个结果
		(select * from student where sex="男" order by age desc limit 100)
		union
		(select * from student where sex="女" order by age asc limit 100)

	说明:
			如果查询中有排序
			1. 需要将每个查询使用()扩起来
			2. 必须在每个查找中结合limit语句使用

5. 例子: 分别查询男同学 和 年龄 大于30的人, 将两个结果集合到一起.
select * from student where sex="男"
union
select * from student where age > 30;

union [选项 all | distinct 默认]



猜你喜欢

转载自blog.csdn.net/qq_39286483/article/details/103914718