完整的 select 查询语句:
select [选项 all | distinct] #distinct 去重
字段表达式(要么不出现,出现就必须在固定的顺序位置上:
from 子句
where 子句 ===>岁数据进行过滤
group by 子句 ===>分组,用于统计
having 子句 ===>分组后在过滤
order by 子句 ===>排序 asc==> 升序 desc ==>降序
limit 子句 ==>限制语句,限制显示条数==>0,4==>从索引0开始,每次显示4条
# group_concat("字段名") ===>将组内的字段通过拼接,组成一个字符串
union 联合查询
将多个查询结果集合到一起
语法
select 查询语句
union
select 查询语句
union
select 查询语句
union
select 查询语句
子查询的分类:
按位置分:
where 型子查询: 子查询出现在where子句中
select * from student where age < (select avg(age) as avg from student);
按结果分:
列子查询: 子查询结果为一列多行
说明: 列子查询其实返回的是一个集合,判断使用 in 或者 not in
案例: 查询没有学生的 班级信息
select * from class where class_id not in (select distinct class_id from student where class_id is not null);
-- 经验: 逆向思维
-- 先查询有学生的 班级信息
a. 查询学生表中的班级id(有班级id就说明有学生)
select distinct class_id from student where class_id is not null;
b. 根据查询到的班级id到班级表中查询班级信息
select * from class where class_id in (1,2,3);
c. 子查询形式
select * from class where class_id in (select distinct class_id from student where class_id is not null);
行子查询: 子查询结果为一行多列
说明:
需要使用 小括号() 行构建符, 将多个字段的值构建成一行, 与行子查询的结果做对比.
表子查询: 子查询结果为多行多列
-- 案例: 查询每个班中年龄最大的学生的信息.
a. 分组查询每个班中年龄最大的值
select class_id,max(age) as max from student where class_id is not null group by class_id;
b. 根据以上结果 再查询学生的信息
select * from student
where (class_id,age) in (select class_id,max(age) as max from student where class_id is not null group by class_id)
(1,40)
in
[
(1,40),
(2,45),
(3,50)
]