基础查询
SELECT * FROM students; SELECT * FROM classes;
|
|
条件查询
select * from students where score >= 80;
or 或关系 and 与关系 not 非关系
要组合三个或者更多的条件,就需要用小括号()
表示如何进行条件运算。
select * from students where score >= 80 and score <=90;
投影查询(即查询表中的某几列)
SELECT id,name,gender,score FROM students;
排序:查询时按表中的某一项作升序或降序排列
按class_id升序
SELECT * FROM students ORDER BY class_id;
按class_id降序
SELECT * FROM students ORDER BY class_id desc ;
分页查询
SELECT * FROM students limit 3 offset 3;
limit 3 每次获取的数据最多为3条
offset 3 获取从第4条开始的数据包括第4条
聚合查询
统计人数
SELECT COUNT(*) '总计' FROM students
COUNT(*) '总计' :总计为COUT(*)的别名
求和
SELECT SUM(score) '二班总分' FROM students where class_id = 2;
平均值
SELECT CEILING(avg(score)) '二班平均分' FROM students where class_id = 2;
CEILING :无论小数位是几都向上进一位
FLOOR :无论小数位是几都向下退一位
最大值
SELECT max(score) '第一名' FROM students ;
最小值
SELECT min(score) '最后一名' FROM students ;
多表查询
select * from students , classes;
注:没什么用
连接查询
内连接
SELECT * FROM students INNER JOIN classes ON students .class_id = classes .id;
那么INNER JOIN是选出两张表都存在的记录:
左外连接
SELECT students.id,class_id,name FROM students LEFT OUTER JOIN classes ON students .class_id = classes .id;
LEFT OUTER JOIN是选出左表存在的记录:
右外连接
SELECT students.id,class_id,name FROM students RIGHT OUTER JOIN classes ON students .class_id = classes .id;
RIGHT OUTER JOIN是选出右表存在的记录:
FULL OUTER JOIN则是选出左右表都存在的记录: