文章目录
一、 基本查询
1.1 查询所有数据
格式为:select * from 表名,意为查询表的所有数据。
1.2 查询指定列的信息
格式为:select+列名1+列名…+from+表名
1.3 条件查询
格式为:select * from 表名 where 指定条件
1.4 运算符查询
- 查询成绩不及格的同学:select * from stu where score<60;
- 查询成绩不为90的同学:
(1)select * from stu where not score=90;
(2)select * from stu where !=90;
(3)select * from stu where <>90; - 查询成绩在80和90之间的同学:
(1)select * from stu where score between 80 and 90;
(2)select * from stu where score score >=80 and score <=90; - 查询成绩为88,95,100的同学:
(1)select * from stu where score=88 or score=95 or score=100;
(2)select * from stu where score in(88,95,100);
二、模糊查询 、滤重和别名
2.1 模糊查询
-
like用来模糊查询,查询所有姓刘的学生的信息:
(1)select * from stu where name like ‘刘%’;
(2)select * from stu where name like ‘刘_’;
其中第一个只要是以刘开头的就可以被搜索到,第二个必须是以刘开头的两个字才可以被搜索到。 -
查询成绩不为null的学生:select * from stu where score is not null;
-
查询成绩为null的学生:select * from stu where score is null;
2.2 滤重、别名以及列运算
- 过滤掉重复的数据,如过滤掉重复的性别:select distinct gender from stu;
- 给列名起别名,如将字段英文换成中文:select name as 姓名,gender as 性别 from stu;
格式为:select 列名 as 别名+from+表名,就算取别名了,数据库里的列名是没有发生变化的,只是那么显示,as后边接的字符串也不用加引号。 - 列运算,如给所有的同学分数+10分:select name,score+10 from stu;
- 关于null的处理,如:select name,ifnull(score,0) from stu; 这个的意思是如果列名为空,就给它一个默认值,这样也方便参与一些运算。
三、排序查询及聚合函数
3.1 排序查询
-
根据score降序查询:select * from stu order by score desc;
desc为降序,asc为升序,如果不做要求默认为升序。 -
根据指定条件排序,现在想对所有的男生的成绩升序查询为:select * from stu where gender=‘男’ order by score;
-
多重排序,如根据age升序,如果age一样,根据score降序:select * from stu order by age asc,score desc;
3.2 聚合函数
- 统计数量:
(1)select count(*) from stu; 统计数据总量
(2)select count(score) from stu; 统计分数不为空的数量 - 统计和,如统计班上的总分:select sum(score) from stu;
- 统计平均分,如统计班上的平均分:
(1)select avg(score) from stu;
(2)select sum(score)/count(*) from stu;
这两种的区别是第一种如果数据为null就不参与运算了,第二种为null的数据也加入运算了。
3.3 保留小数点数
round(avg(score),2)即表示将求出来的分数平均分保留两位小数。
3.4 其他聚合函数
- max(score):求分数这一列的最大值
- min(score):求分数这一列的最小值
注意点:在聚合函数里,null是不参与运算的;如果想让null参与运算,可以使用ifnull(列名,默认值)给null设定一个默认值。
四、分组查询及查询语句的执行顺序
4.1 分组查询
-
分组查询平均分,如根据性别分组查询,格式为:select+列名+from+group by+列名,SQL语句为:select gender,arg(score) as 平均分 from stu group gender;
-
根据特定条件分组查询平均分大于60分的:select gender,arg(score) as 平均分 from stu group gender having 平均分>60;
where后边是专门是接查询条件的,但是在分组查询中一般用having代替,放在group by 后边。
4.2查询语句的执行顺序
(1)第一步为from+表名,查询表中的所有数据
(2)第二步为where+指定条件,查询出指定条件的数据,其中起别名:as+别名是第2.5步,所以where后边不能接别名,因为别名都还没有执行。
(3)第三步为group by+列名,按照指定列名分组,其中聚合函数avg(列名)是3.5步,所以分组后边不能接聚合函数。
(4)第四步为having+条件,这个时候having后的查询条件既可以有别名,也可以有聚合函数。
(5)第五步为order by+列名+desc/asc,排序语句是最后执行的,所以后边也可以接别名。
where先执行可以先将数据筛选减少计算量以提高查询效率。
4.3 where和having的区别
(1)having通常与group by结合使用。
(2)where是在分组之前进行过滤的,having是在分组之后过滤的。
(3)having可以接聚合函数和别名,where都不可以,所以having的查询范围更广。