select
[distinct] 字段名
from 表名
where 查询条件
group by 分组字段
having 筛选条件
order by 排序字段
limit 限制条件
查询顺序为
from -- 拿到表的数据
where -- 对根据条件表数据进行筛选
group by -- 根据某个字段进行分组
having -- 对分组之后的数据进行再次筛选
order by -- 对数据排序(排序不止有order by)
limit -- 限制数据条数
distinct -- 对数据去重
-- 执行聚合函数对结果进行聚合
select -- 查询的结果(select结果的本质是一张虚拟表)
单表查询
基本查询
//查询时重命名列
select s_id as myid ,c_id from score;//字段去重查询
select distinct type from temp;//查询表中所有记录的name和数学英语的总分
select name,math+english from 表名;
where条件查询
select * from score where s_score >60; 查询出分数大于60的数据
select * from student where age>=20&& age<=30; 查询年龄在20到30之间的所有学生
select * from student where age>=20 and age<=30; 查询年龄在20到30之间的所有学生
select * from student where age in (18,19,20); 查询年龄为181920岁所有学生
select * from student where age=18 or age=19 or age=20; 查询年龄为181920岁所有学生
select * from student where age is not null; 查询年龄字段不为空的所有学生
select * from student where name like "马%"; 查询姓马的所有学生
select * from student where name like "_化%"; 查询名字第二个字为化的所有学生
select * from score where s_score >80 and s_id ='01'; 查询成绩大于80,并且s_id是01的数据
select * from score where s_score >80 or s_id ='01'; 查询成绩大于80,或者s_id 是01的数
简单排序查询
select * from student order by math; 查询所有学生并按数学成绩排序,默认是升序
select * from student order by math desc; 查询所有学生并按数学成绩排序,并指定降序排列
聚合函数查询 (多进一出的函数)
select count(id) from student; 查询学生的总人数
select max(math),min(math) from student; 查询数学成绩的最大值和最小值
select sum(math),avg(math) from student; 对数学成绩进行求和,求平均值
分组查询 group by
分别查询所有男生的数学平均分和所有女生的数学平均分
select sex,avg(math) from student group by sex;
分别查询男女学生数学平均分,成绩小于70的学生不参与计算
select sex,avg(math) from student where math>70 group by sex;
分别查询男女学生的总人数
select sex,count(id) from student group by sex;
having查询 having用于对分组后的数据过滤 求平均分数大于85的学生信息
select s_id ,avg(s_score) as avgscore from score group by s_id having avgscore >85;
LIMIT语句
select * from score limit 3;// 限制返回三条记录
select * from student limit (x,y);//从索引x开始显示y条数据 索引从0开始
union语句 Union:对两个结果集进行并集操作,不包括重复行,同时进行默认规则的排序; Union All:对两个结果集进行并集操作,包括重复行,不进行排序;