增
删
改
查
1.条件查询: where 、=、<、>、!=、<>、between xx and xx、or、 and、in (xx,xx,xx)、not in (xx,xx,xx)
2.通配符:like、%,_
3.分页:limit、offset
4.排序:order by 、desc、asc
如果要取后10行:先将所有行反转,再按照分页取《----即先降序排序后分页
select * from tb1 order by id desc limit 10;
先按照年龄从大到小,如果有年龄相同的则按照id从大到小
select * from tb1 order by age desc, id desc;
5.分组:group by、having
聚合函数:count/max/min/sum/avg
注:
如果对于聚合函数结果进行二次筛选时,必须使用having!!!
使用where进行条件查询时不能出现聚合函数!!!
group by 必须在 where之后,order by 之前!!!
示例1:
部门表department(id, title)
用户表userinfo(id, name, depart_id)
统计部门a的人数:
select count(id), depart_id from userinfo group by depart_id;
部门总人数大于10的查询出来:
select count(id), depart_id from userinfo group by depart_id having count(id) > 10;
select count(id) as count, depart_id from userinfo where id > 0 group by depart_id having count(id) > 10;
统计用户个数:
select count(id) from userinfo;
6.连表操作
左连接和右连接的区别是什么?
左连接是左表全显示,如果右表没有对应元素则显示Null,右连接则相反
内连接:如果连接完后出现null的整行直接隐藏掉
把所有用户列出了,且显示出用户所在部门的中文:
select name, title from userinfo left join department on userinfo.depart_id = department.id ;
对上图进行连表操作:
select
score.sid,
course.cid,
student.sid
from
score
left join student on score.student_id = student.sid
left join course on score.course_id = course.cid
left join class on student.class_id = class.cid
left join teacher on course.teacher_id = teacher.tid;
最后的最后:
在创建成绩表的时候可以将 student_id和course_id创建联合唯一索引
练手题:
用户表t_user表,年龄age(int类型),求哪个年龄的用户最多
解题思路:
1.先按照年龄分组;
2.随后按照每个年龄个数进行降序排序;
3.取排好序的第一行即为用户最多的年龄。
select age, count(age) from t_user group by age order by count(age) desc limit 1;
写一个SQL,找出语文排名第二的学生姓名
- 三张表 Student(id,name), Course(id,name), Score(sid、cid、score)
解题思路:用order by limit,和上面思路类似,只不过少了分组的操作
select student.sname from student where sid=(select score.student_id from score left join course on course.cid=score.course_id where cname="语文" order by num desc limit 1,1);