一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第10天,点击查看活动详情。
1. 条件数据查询
使用下图表格数据用于条件查询 创建表格数据
语法:select f1,f2,f3,...
from table_name
where 条件;
关系运算符:>,<,=,>=,<=,!= 逻辑:and or not 确定范围:between v1 and v2 , not between v1 and v2; 空值:is null , is notNull 确定集合:in , not in 字符匹配:like , not like %代表任意长度 _代表任意单个字符 order by 对查询结果排序 默认asc(升序),desc(降序) 多字段排序:先按照sal 升序排序,再按照Hiredate 降序排序;
select * from t_employee
where sal > 100;
where sal >100 and sal<200;
where sal between 100 and 200;
where comm is null;
where sal in (800,950);
where ename like ‘A%’;
where ename like ‘%k%’;
order by sal desc;
1.1 带关系运算符和逻辑运算符的条件数据查询
关系运算符:> >= < <= = !=(<>) 逻辑运算符:and(&&) or(||) not(!) 例子1:查询员工表中职位是clerk的员工
select ename,job
from t_employee
where job='clerk';
关系运算符:>,<,=,>=,<=,!=
例子2:查询员工表中从事于clerk工作并且工资是大于1000的员工。
select ename,job,sal
from t_employee
where job='clerk' and sal>1000;
逻辑:and or not
1.2 带between...and关键字的条件数据查询
确定范围:between v1 and v2 , not between v1 and v2;
语法:select f1,f2,f3,...
from table_name
where f列 between v1 and v2;
【说明:f列的值要在v1和v2范围内 between and只针对数字类型】
例子1:查询员工表中工资在1000和2000之间的员工
select ename,sal
from t_employee
where sal between 1000 and 2000;
另一种写法:
select ename,sal
from t_employee
where sal>=1000 && sal<=2000;
例子2:查询员工表中工资不在1000和2000之间的员工
select ename,sal
from t_employee
where sal not between 1000 and 2000;
或:
select ename,sal
from t_employee
where sal<1000 or sal>2000;
1.3 带is null关键字的条件数据查询
空值:is null , is notNull
作用:用来判断字段的数值是否为空的条件查询
语法:
select f1,f2,f3...
from table_name
where f is null;
说明:判断f列的数值是否为空的条件查询
例子1:查询员工表中那些员工没有提成
select ename,comm
from t_employee
where comm is null;
例子2:查询员工表中哪些员工有提成
select ename,comm
from t_employee
where comm is not null;
select ename,comm
from t_employee
where not comm is null;
1.4 带in关键字的条件数据查询
确定集合:in , not in
作用:用来实现判断字段的值是否在指定集合中的条件查询
语法:
select f1,f2,f3...
from table_name
where f in(v1,v2,v3,v4,...vn);
例子1:查询员工表中员工编号为7521,7782,7566和7788的员工
select empno,ename
from t_employee
where empno in(7521,7782,7566,7788);
或者
select empno,ename
from t_employee
where empno=7521 or empno=7782 or empno=7566 or empno=7788;
例子2:查询员工表中员工编号不是7521,7782,7566和7788的员工
select empno,ename
from t_employee
where empno not in(7521,7782,7566,7788);
【使用in关键字的注意事项】 在使用in时,查询的集合中如果存在null,不会影响结果; 在使用not in时,查询的集合中如果存在null,则不会有任何的查询结果 例子3:查询员工表中工资是800,950的员工
select ename,sal
from t_employee
where sal in(800,950);
查询结果和in(800,950,null)是一样的。 例子4:查询员工表中工资不是800,950的员工
select ename,sal
from t_employee
where sal not in(800,950);
not in中有null会查询不出来结果
select ename,sal
from t_employee
where sal not in(800,950,null);
1.5 带like关键字的条件数据查询
字符匹配:like , not like
%代表任意长度
_代表任意单个字符
作用:用于做模糊匹配的数据查询
语法:
select f1,f2,f3...
from table_name
where f like v;
说明:f表示字段 v表示模糊匹配的条件
通配符:通配符要写在单引号''中
1)_:能够匹配单个字符
2)%:能够匹配任意长度的字符,可以是0到
多个
例子1:查询员工表中员工姓名是以a开头的员工
select ename
from t_employee
where ename like 'a%';
例子2:查询员工表中员工姓名的第二个字母是a的员工
select ename
from t_employee
where ename like '_a%';
例子3:查询员工表中员工姓名包含k字母的员工
select ename
from t_employee
where ename like '%k%';