6.17
学习目标
起别名
因为在创建时候不能起中文名字,但是可以在select中命中文名
SELECT age as 年龄,class as 班级 FROM students;as可以不加
给表起别名
select * from students as stu;
distinct过滤重复记录
条件查询
比较运算符
逻辑运算符
都要写
模糊查询like
%表示任意多个字符 _任意一个字符,可以连用eg:__ 说明有两个字符
secelct * from students where name like '王昭%'注意没有等号
查询name中有‘白’字的学生
........'%白%'
范围查找
in表示一个非连续范围
查询家乡是北京上海安徽
select * from students where hometown in ('上海',‘北京’,‘安徽’)
between...and...表示在一个连续范围内
查找age在25-30的学生记录
select * from students where age between 25 and 30;闭区间
查询年龄25到30之外的
select * from students where not age between 25 and 30;取反
查询年龄20或25或30的女生
select * from students where age in(20,25, 30) and sex='女'
空判断
null不是0,也不是'',null在SQL代表空,什么也没有。
不能用比较运算符的判断,=null以及!=null 均报错
查询身份证非空的学生记录
select * from students where card is not null
where用到update和delete后面
update students set class='1班' where name like '孙%'
括起来条件
排序order by
为了方便查看,对数据进行排序
默认是asc 从小到大
where 结合order by排序
要先写where再写orderby
聚合函数
为了快速得到统计数据,经常用到一下5个聚合函数 聚合函数不能在where后面的条件中使用
count总记录数
写*和name没区别,本质上都是统计有多少个记录 求select返回的记录总数
max最大值 min最小值
sum求和 avg求平均值同
sum(字段名)指定字段的值求和
练习
select max(age) 最大年龄,min(age),avg(age) from students
select count(*) from students where class='1班'
select count(*) from students where age<30 and class='3班'
数据分组 group by
按照字段分组,表示此字段相同的数据会被放到一个组中
目的是配合聚合函数,聚合函数会对每一组的数据分别进行统计
SELECT sex,count(*) FROM students where class='1班' group by sex;
顺序
select * from 表名 where 条件 group by 字段 order by 字段
练习1
select class,count(*),avg(age),max(age),min(age) from students where class <> '3班' group by class order by class desc
分组后的数据筛选
having,groupby和聚合函数息息相关
where先筛选符合条件的记录,然后在聚合统计;having先分组聚合统计,在统计结果中筛选
where后面不能用聚合函数,但是having可以
对比having和where
练习2
select class,count(*) from students group by class having count(*)>2
查询平均年龄大于30岁的班级名称和班级总人数
select class,count(*),avg(age) from students group by class having avg(age)>30
数据分页显示
获取部分行
数据量过大时候,在一页查看比较麻烦
查询年龄最大的名字
select name from students order by age desc(此时从大到小排序)limit 1;
查询年龄最小的女同学
select * from students where sex='女' order by age limit 1;
当where,group/order by时候,limit在最后
分页技术(公式)
数据库真多内容啊,我要学吐了·········之前本科学过,这一遍权当过一遍了~不学了,好累~自己之前不好好学,现在都要补回来了,能怎么办(摊手555 明天再写
6.18 Im back
例题
已知每页页数,求一张表需要几页显示完
步骤:(1)求总页数(2)总页数/每页的记录数(3)结果向上取整
select count(*) from students;