2020-10-10
Msql数据管理3
between … and
BETWEEN 操作符在 WHERE 子句中使用,作用是选取介于两个值之间的数据范围。这些值可以是数值、文本或者日期。(文本仅支持英文)
语法
WHERE 字段名 BETWEEN 值1 AND 值2
示例: WHERE age BETWEEN 10 AND 20
age字段的值 在10 到 20 之间会被查出来,并且包含10和20
查询数值和日期 的范围 包含 值1 和 值2,及中间的值
实战
查询 生日在 1990-01-01 到 2000-01-02 之间的学生信息
select * from student where birthday between '1990-01-01' and '2000-01-02';
查询 sc表 成绩 在 80 到 90 分之间 的数据信息
select * from sc where score between 80 and 90;
查询学生表 sid 在 5 和 10 之间的学生信息
select * from student where sid between 5 and 10;
in
in 操作符允许我们在 WHERE 子句中规定多个值。
语法1:
where 字段名 in (值1,值2,值3....)
示例: where age in (20,21,25);
age 字段的值 只要是 20或者21或者25 的数据 都满足条件
语法2:
where not in (值1,值2,值3....)
示例: where age in (20,21,25);
age 字段的值 只要 不是 20或者21或者25 的数据 都满足条件
实战:
查询sc表中成绩在 70,80,90的数据
select * from sc where score in (70,80,90);
查询sc表中成绩不在 70,80,90的数据
select * from sc where score not in (70,80,90);
查询 学生表中 生日 在 1990-01-01,1990-12-21,2017-12-20,2012-06-06这四天的学生信息
select * from student where birthday in ('1990-01-01','1990-12-21','2017-12-20','2012-06-06');
查询 学生表中 生日 不在 1990-01-01,1990-12-21,2017-12-20,2012-06-06这四天的学生信息
select * from student where birthday not in ('1990-01-01','1990-12-21','2017-12-20','2012-06-06');
limit
MySQL中的分页查询, limit 通常放在sql 语句的最末尾
语法1:
limit 4查询前4条数据
语法2:
limit 4,3从第4条数据之后开始,查询3条数据
也就是 第5,6,7条的数据
语法3:
limit 4 offset 10;offset后面的数字是指记录数
从第10条 之后的数据开始 查询4条数据
也就是 第 11,12,13,14条数据
实战
查询 学生表 中的前五条数据
select * from student limit 5;
查询 学生表 中10到15条数据,包含第十条和第十五条
select * from student limit 9,6;
查询 学生表 中10到15条数据,包含第十条和第十五条 ,使用offset关键字
select * from student limit 6 offset 9;
is null
如果字段没有要求非空,则字段值 可以为空,就是null值。如果要查询某个 字段 为 null的数据,不能使用 字段名=null,要用 字段名 is null;
语法1:
where 字段名 is null;
字段名 为空的符合条件
语法2:
where 字段名 is not null;
字段名 不为空的符合条件
实战
student表新增两条数据,要求birthday字段为空
insert into student (sname) values('小明' ); insert into student (sname,sex) values('小红','女' ); insert into student (sname) values('小强' );
查询 student表 生日字段 为空 的学生
select * from student where birthday is null;
查询 student表 生日字段 不为空 的学生
select * from student where birthday is not null;
查询 student表 生日字段 不为空 的 女生
select * from student where birthday is not null and sex = '女';
查询 student表 生日字段 不为空 的 男生
select * from student where birthday is not null and sex = '男';
别名
起别名是为了后续学习多表联查 做铺垫,语法十分简单
给字段起别名
比如查询 student 表的 学生姓名 和 生日 的sql语句:
select sname,birthday from student;
给 sname,birthday字段 起别名 ,改为中文
select sname as 姓名,birthday as 生日 from student;
起了别名后,查出来的字段会以别名展示。
as 关键字也可以省略,字段名 和 别名之间 用空格隔开即可
select sname 姓名, birthday 生日 from student;
给表起别名
例子:
select a.sname, a.birthday from student as a;
给表 起别名 同样是 使用 as关键字(可以使用空格隔开代替as关键字), a 就代表 student表,查询字段时,可以 使用 a.sname 代表 student的sname字段。
给表起别名 通常用在 多表查询,本次使用演示,先熟悉语法。