students:
id | class_id | name | gender | score |
---|---|---|---|---|
1 | 1 | 小明 | M | 90 |
2 | 1 | 小红 | F | 95 |
3 | 1 | 小军 | M | 88 |
4 | 1 | 小米 | F | 73 |
5 | 2 | 小白 | F | 81 |
6 | 2 | 小兵 | M | 55 |
7 | 2 | 小林 | M | 85 |
8 | 3 | 小新 | F | 91 |
9 | 3 | 小王 | M | 89 |
10 | 3 | 小丽 | F | 88 |
1、基本查询:
①、查询所有记录
SELECT * FROM students;
②、查询特定字段
SELECT class_id,name FROM students;
③、查询时指定别名
SELECT
class_id AS ‘班级编号‘,
name AS ‘姓名‘
FROM students;
④、对查询结果做运算
SELECT name, score*2 FROM students;
2、条件查询:
- 算术运算符:+、-、*、/、%
- 比较运算符:>、>=、<、<=、=、!=、IN(a,b,c)、IS NULL、IS NOT NULL、BETWEEN ... AND ...、LIKE、REGEXP
- 逻辑运算符:AND、OR、NOT、XOR
- 按位运算符:&、|、~、^ 、<<、>>
SELECT * FROM students WHERE (class_id=1 OR class_id=2) AND score>85;
WHERE子句中的条件表达式的执行顺序从左到右,应尽量把索引条件、筛选掉最多记录的条件写在左侧。
3、分页查询:
# LIMIT + 起始位置,偏移量
SELECT * FROM students LIMIT 0,5;
# 查询前五条数据 简写
SELECT * FROM students LIMIT 5;
4、排序:
# 默认升序
SELECT * FROM students ORDER BY score;
# 降序
SELECT * FROM students ORDER BY score DESC;
# 指定多个排序规则,当第一个规则无法排序时使用第二个,以此类推,最后使用主键排序
SELECT * FROM students
ORDER BY score DESC,class_id DESC;
5、去重:
# DISTINCT用于筛去结果集中完全相同的记录
SELECT DISTINCT score FROM students;
SELECT DISTINCT score,class_id FROM students;
查询语句的执行顺序:FROM -> WHERE -> SELECT -> ORDER BY -> LIMIT