基础排序
查询后排序
asc 升序 ascending
desc 降序 descending
1
|
select device_id, age from user_profile order by age asc
|
牛客网题目链接
牛客网题目链接 (降序排列)
查询后多列排序
- 多列排序使用
, 隔开
- 不指定排序顺序,默认是
asc
1
2
3
4
5
|
select device_id,gpa,age from user_profile order by gpa asc, age asc
SELECT device_id,gpa,age from user_profile order by gpa,age;默认以升序排列
SELECT device_id,gpa,age from user_profile order by gpa,age asc;
SELECT device_id,gpa,age from user_profile order by gpa asc,age asc;
|
牛客网题目链接
基础操作符
查找学校是北大的学生信息
- 我们可以通过
where 子句来筛选对应的记录
1
|
select device_id, university from user_profile where university = '北京大学'
|
-
该题背景 : device_id 和 university 为联合索引
在这个背景下面,我们可以在查询的时候使用联合索引,少去一层回表查询的操作 todo , DBM 不会自己合上id吗
1
|
Select device_id,university FROM user_profile where university = "北京大学" and device_id = user_profile.device_id;
|
牛客网题目链接
查询年龄大于 24岁的用户信息
- 引入逻辑运算符
> 以此类推还有 < , = , >= , <= , != , =
1
|
select device_id, gender, age,university from user_profile where age > 24
|
[牛客网题目链接](select device_id, gender, age,university from user_profile where age > 24)
查询某个年龄段的用户信息
- 使用
between and 和 >= and <= 没什么本质区别,性能和业务使用上无差别
- 不过相较于
between and 逻辑表达式更灵活
1
2
3
4
5
|
select device_id, gender, age from user_profile where age >= 20 and age <= 23
SELECT device_id, gender, age
FROM user_profile
WHERE age BETWEEN 20 AND 23;
|
牛客网题目链接
查找除复旦大学的用户信息
NOT IN 可以比较多个值, 对于 <> != 如果需要比较多个值需要引入 and
<> 和 != 没有本质区别,不过一般都是写 <> 除非团队开发有要求,那么使用 != 尽可能统一组内的代码风格
1
2
3
|
select device_id,gender,age,university from user_profile where university <> '复旦大学'
select device_id,gender,age,university from user_profile where university != '复旦大学'
select device_id,gender,age,university from user_profile where university NOT IN ("复旦大学")
|
牛客网题目链接
用 where 过滤空值
- 可以单独是用
is not null 或者是单独使用 <> ""
- 但是实际业务最好是两个一起使用 ~
1
2
3
|
select device_id,gender,age,university
from user_profile
where age is not null and age <> ""
|
牛客网题目链接