MySQL学习笔记(16)-联合查询

联合查询

联合查询:将多次查询(多条select语句),在记录上进行拼接(字段不会增加)

基本语法

多条select语句构成:每一条select语句获取的字段数必须严格一致(但是与字段类型无关)

Select 语句1

Union[union选项]

Select 语句2

Union选项:与select选项一样有两个

    All:保留所有(不管重复)

    Distinct:去重(整个重复):默认的

-- 联合查询
select * from my_class
union
select * from my_class;
select * from my_class
union all -- 不去重
select * from my_class;
select * from my_class
union distinct -- 去重
select * from my_class;

联合查询只要求字段一样,跟数据类型无关

select id,c_name,room from my_class
union all -- 不去重
select name,number,id from my_student;

意义

联合查询的意义分为两种:

1.查询同一张表,但是需求不同:如查询学生信息,男生身高升序,女生身高降序。

2.多表查询:多张表的结构是完全一样的,保存的数据(结构)也是一样的。

Order by使用

在联合查询中:order by不能直接使用,需要对查询语句使用括号才行,若要order by 生效:必须搭配limit:limit 使用限定的最大数即可。

 
 
-- 需求:男生升序,女生降序(年龄)
(select * from my_student where sex = '男' order by  age asc limit 9999999)
union
(select * from my_student where sex = '女' order by age desc limit 9999999);



猜你喜欢

转载自blog.csdn.net/qq_38826019/article/details/80629176