DQL语言学习进阶二(条件查询)
一、语法
select 查询列表 from 表名 where 筛选条件;
(顺序:from,where,select)
二、分类
(一)按条件表达式筛选
简单条件运算符:> < = != <> >= <= <=>
例1:查询工资大于12000的员工信息
select*from employee where salary >12000;
例2:查询部门编号不等于90号的员工名和部门编号
select last_name,department_id from employee where department_id !=90;
(二)按逻辑表达式筛选
逻辑运算符: and or not
作用:用于连接条件表达式
and(&&):两个条件都为true,结果为true,反之为false;
or(||):只要有一个条件为true,结果为true,反之为false;
not(|):如果连接的条件本身为false,结果为true,反之为false。
例1:查询工资在10000到20000之间的员工名、工资及奖金
select last_name,salary,commission_pct from employee where salary>=1000and salary<=20000;
例2:查询部门编号不是在90到110之间,或者工资高于15000的员工信息
方式一: select*from employee where department_id<90or department_id>110or salary>15000;方式二: select*from employee wherenot( department_id>=90and department_id <=110)or salary>15000;
(三)模糊查询
复杂条件运算符:like between and in is null / is not null
1、like:
(1)一般和通配符搭配使用,可以判断字符型或数值型通配符:
%:任意多个字符,包含0个字符
_:任意单个字符
例1:查询员工名中包含字符a的员工信息
select*from employee where last_name like'% a %';
例2:查询员工名中第三个字符为e,第五个字符为a的员工名和工资
select last_name, salary from employee where last_name like'__e_a%';
例3:查询员工名中第二个字符为_的员工名
方式一: select last_name from employee where last_name like'_\_%';方式二: select last_name from employee where last_name like'_$_%' escape '$';
(#escape 转义)
2、between and
(1)使用 between and 可以提高语句的简洁度
(2)包含临界值
(3)两个临界值不要调换顺序
例1:查询员工编号在100到120之间的员工信息
方式一: select*from employee where employee_id >=100and employee_id <=120;方式二: select*from employee where employee_id between100and120;
3、in
含义:判断某字段的值是否属于in列表中的某一项
特点:
(1)使用in提高语句简洁度
(2)in列表中的值类型必须一致或兼容
(3)不支持通配符的使用
例:查询员工的工种编号是IT_PROG,AD_VP,AD_PRES中的一个员工名和工种编号
方式一: select last_name, job_id from employee where job_id ='IT_PROG'or job_id ='AD_VP'or job_id ='AD_PRES';方式二: select last_name, job_id from employee where job_id in('IT_PROG','AD_VP','AD_PRES');
4、is null
=或<>不能用于判断null值
is null或is not null可以判断null值
例1:查询没有奖金的员工名和奖金率
select last_name, comission_pct from employee where comission isnull;
例2:查询有奖金的员工名和奖金率
select last_name, comission_pct from employee where comission isnotnull;
安全等于:<=>
例1:查询没有奖金的员工名和奖金率
select last_name, comission_pct from employee where comission <=>null;
例2:查询工资为12000的员工信息
select last_name, salary from employee where salary <=>12000;
is null PK <=>
is null:仅仅可以判断null值,可读性高
<=>:既可以判断null值,又可以判断普通数值,可读性较低