查询常用代码
SELECT * FROM students;
SELECT * FROM students WHERE score >= 80;
SELECT * FROM students WHERE score >= 80 AND gender = 'M';
SELECT * FROM students WHERE score >= 80 OR gender = 'M';
SELECT * FROM students WHERE NOT class_id = 2;
SELECT * FROM students WHERE (score < 80 OR score > 90) AND gender = 'M';
查询分数在70分(含)~90分(含)之间的学生可以使用的WHERE语句
SELECT * FROM students WHERE score >= 70 AND score <= 90 ;
SELECT * FROM students WHERE score BETWEEN 70 AND 90;
投影查询
SELECT id, score, name FROM students;
//SELECT语句将列名score重命名为points,而id和name列名保持不变
SELECT id, score points, name FROM students;
排序
SELECT id, name, gender, score FROM students ORDER BY score;
SELECT id, name, gender, score FROM students ORDER BY score DESC;
//表示先按score列倒序,如果有相同分数的,再按gender列排序
SELECT id, name, gender, score FROM students ORDER BY score DESC, gender;
如果有WHERE子句,那么ORDER BY子句要放到WHERE子句后面。例如,查询一班的学生成绩,并按照倒序排序:
SELECT id, name, gender, score
FROM students
WHERE class_id = 1
ORDER BY score DESC;
分页查询
SELECT id, name, gender, score
FROM students
ORDER BY score DESC
LIMIT 3 OFFSET 0;
因此,分页实际上就是从结果集中“截取”出第M~N条记录。这个查询可以通过LIMIT M OFFSET N 子句实现。
N表示列表开始的索引
LIMIT总是设定为pageSize;
OFFSET计算公式为pageSize * (pageIndex - 1)
mysql 中 LIMIT 15 OFFSET 30还可以简写成LIMIT 30, 15;
聚合查询
SELECT COUNT(*) num FROM students;
//其中num为别名
其他函数
函数 说明
SUM 计算某一列的合计值,该列必须为数值类型
AVG 计算某一列的平均值,该列必须为数值类型
MAX 计算某一列的最大值
MIN 计算某一列的最小值
分组聚合
SELECT class_id, COUNT(*) num FROM students GROUP BY class_id;
SELECT class_id, gender, AVG(score) averge FROM students GROUP BY class_id, gender;//算出各个班男女生的平均分;
执行这个查询,COUNT()的结果不再是一个,而是3个,这是因为,GROUP BY子句指定了按class_id分组,因此,执行该SELECT语句时,会把class_id相同的列先分组,再分别计算,因此,得到了3行结果。
但是这3行结果分别是哪三个班级的,不好看出来,所以我们可以把class_id列也放入结果集中:
多表查询
SELECT
students.id sid,
students.name,
students.gender,
students.score,
classes.id cid,
classes.name cname
FROM students, classes;
//给表起别名
SELECT
s.id sid,
s.name,
s.gender,
s.score,
c.id cid,
c.name cname
FROM students s, classes c;
连接查询
SELECT s.id, s.name, s.class_id, c.name class_name, s.gender, s.score
FROM students s
INNER JOIN classes c
ON s.class_id = c.id;
1.先确定主表,仍然使用FROM <表1>的语法;
2.再确定需要连接的表,使用INNER JOIN <表2>的语法;
3.然后确定连接条件,使用ON <条件…>,这里的条件是s.class_id = c.id,4.表示students表的class_id列与classes表的id列相同的行需要连接;
5.可选:加上WHERE子句、ORDER BY等子句。
本文参考廖雪峰mysql教程https://www.liaoxuefeng.com/wiki/1177760294764384/1179610888796448