#查询所有数据
select * from test.total; #from A.B A库名 B表名
#查询部分数据
select
id, #要查询的列名
age,
university
from test.total
-- where university = 'CUMT' #只有一个=
-- where age >= 20
where university = 'CUMT' and age > 20
limit 3 #限制前3个
1. distinct去重查询
建议仅放一个列名
select
distinct age #相当于python中的.unique()
from test.total
2. AS别名
select
tt.id as '编号', #同python
tt.dept as "学号"
from test.total as tt
3. limit偏移限制
limit 4,3 偏移数+限制数
use test;
select * from total
运行结果:
use test;
select * from total limit 2,3
运行结果:
4. oder_by排序
select * from test.total #无;
order by age desc; #按age列从大到小
order by age; #从小到大
order by gpa desc,age desc; #先按gpa排序,再按age排序,有;
5. where查询
where university = 'CUMT' #只有一个=
where age >= 20 #比大小
where age between 20 and 40 #区间
where university = 'CUMT' and age > 20 #多个条件
where day > "2001-01-01" #日期数据
where university in ("北京大学","复旦大学","山东大学") #多个查询
where university not in ("北京大学")
#模糊查询
where university like "%C" #%代表任意数量的字符,主要表示位置
6.分组查询
总感觉这里有点问题,发现问题请戳我督促我修改
#统计总表中每个学校所含的学生数量
select
university,
count(dept) #计数
from test.total
group by #分组
university #可以依据两个列分组
运行结果:
7.过滤查询
where | having |
过滤行 | 过滤分组 |
不可包含聚合函数(见文末) | 可包含聚合函数 |
分组前(group by 之前) | 分组后(group by 之后) |
select
university,
count(dept)
from test.total
#where count(dept) >=2 #代码报错,where语句中不能包括聚合函数count
group by
university
having count(dept) >=2; #对分组结果进行查询
运行结果:与9.分组查询的结果相对比,只保留了大于等于2 的部分
8.正则查询
select * from test.total
-- where university regexp '^C' #以C开头
-- where university regexp 'C$' #以C结尾
9.编写顺序与执行顺序
编写顺序(左)\执行顺序(右,红圈)