查询的进阶操作
结果去重
通过命令 select distinct age from students; 可以去除年龄中重复的值.
命令格式: select distinct 字段名 from 表名;
where之比较运算
where是条件查询的关键词,后边跟上条件.
>
: 大于号, 指定字段值大于指定条件才会被查询到;
命令格式: select * from 表名 where 字段名 > 条件值;
<
: 小于号, 指定字段值小于指定条件才会被查询到;
命令格式: select * from 表名 where 字段名 < 条件值;
>=或者 <=
:同大于,小于一样,只是多了一个等于的情况;
命令格式: select * from 表名 where 字段名 >= 条件值;
=
: 等于,用法同上.
!= 或者 <>
: 不等于,用法同上;
where之逻辑运算
and
: 当有多个条件的时候,表示多个条件必须同时成立;
命令格式: select * from students where 条件1 and 条件2 and 条件3 …
例如 : select * from students where age > 21 and age <28; 查询年龄大于21并且小于28岁的.
or
: 当有多个条件的时候,满足任意一个即可;
命令格式: select * from students where 条件1 or 条件2 or 条件3 …
例如 : select * from students where age = 21 or age =28; 查询年龄是21和28岁的.
not
: 把条件取反;
命令格式: select * from students where not 条件
例如: select * from students where not age > 21; 查询到的是年龄小于等于21岁的
where之模糊查询
like 表示模糊查询
%
表示任意0个或多个;
_
表示任意一个字符;
命令格式: where 字段 like 要查询的数据;
查询名字以 '‘小’'开头的同学的信息, 条件是 “小%”,因为 ''小" 首先能确定一个字, ‘’%’’ 又代表0个或多个任意字符,组合起来就是以 ‘‘小’’ 开头的所有字符都能满足.
查询名字中含有 ‘‘彩’’ 字的, 条件是 “%彩%”,两边都是任意,中间有彩就符合.
查询名字长度为2的,条件是 “__”, 一个 ‘’_’'代表一个任意字符.
查询名字长度为3的,条件是"___".
查询名字长度至少为2的,条件是"__%",也就是大于等于2.
where之范围查询
in
: 用于非连续的范围的查询,相当于多个值的 or 关系,加上not就是取反.
between 起始 and 终值
: 连续,包含起始值和终值,是一种 and 关系,加上not 就是取反.
where之空值判断
判空
is null
.
非空is not null
, not is null 是错误写法,按照英语语法记就行了.
为什么有判断是否为null,因为 null是一种特殊的类型,它不是空串,空格,长度为0的字符串之类.
如有错误还望指出