条件查询分类:
(一) 按条件表达式筛选
简单条件运算符: > < = != <> >= <=
(二) 按逻辑表达式筛选
逻辑运算符:
作用:用于连接条件表达式
&& || !
and or not
&& 和 and: 两个条件都为true,结果为true,反之为false
|| 或 or: 只要有一个条件为true,结果为true,反之为false
! 或 not: 如果连接的条件本身为false,结果为true,反之为false
(三) 模糊查询
like
between and
in
is null
条件查询:
- 语法: select 查询列表 from 表名 where 筛选条件;
- 按条件表达式筛选
简单条件运算符: > < = != <> >= <=
案例1: 查询工资 >12000的员工信息
select * from employees where salary>12000; - 案例2:查询部门编号不等于90号的员工名和部门编号
select
last_name,
department_id
from
employees
where
department_id!=90; // 不等于 != 最好换成<> - 按逻辑表达式筛选
案例1: 查询工资z在10000到20000之间的员工名、工资以及奖金
select
last_name,
salary,
commission_pct
from
employees
where
salary>=10000 and salary<=20000; - 案例2:查询部门编号不是在90到110之间,或者工资高于15000的员工信息
select
*
from
employees
where
department_id < 90 or department_id > 110 or salary>15000; - 模糊查询
(1) like
特点:一般和通配符搭配使用
通配符: % 任意多个字符,%a%包含以a开头的字符
_ 任意单个字符
案例1:查询员工名中包含字符a的员工信息
select
*
from
employees
where
last_name like ‘%a%’; // 字符型的值必须用单引号引起来,%代表通配符,可能是任意多个字符。
含有a的大小写的字段都显示出来了 - 案例2:查询员工中第三个字符为m,第五个字符为n的员工名和工资
select
last_name,
salary
from
employees
where
last_name like ‘__m_n%’; - 案例3:查询员工名中第二个字符为_的员工名
select
last_name,
salary
from
employees
where
last_name like ‘_%’;
其中 last_name like '_%’; 可以换成这一句话 last_name like ‘KaTeX parse error: Expected group after '_' at position 1: _̲%' escape '’;
$可以换成其他的任何字符
(2) between and
案例1:查询员工编号在100到120之间的员工信息
select
*
from
employees
where
employee_id >= 100 and employee_id<=120;
其中 employ_id >= 100 and employee_id<=120; 可以换成这一句话 employ_id between 100 and 120;
between and 包含临界值100 120,两个临界值不可以颠倒位置
(3) in
含义:判断某字段的值是否属于in列表中的某一项
特点:in列表的值类型必须一致或兼容
案例1:查询员工的工种编号 IT_PROG、AD_VP、AD_VP、AD_PRES中的一个员工名和工种编号
select
last_name,
job_id
from
employees
where
job_id = ‘IT_PROT’ or job_id = ‘AD_VP’ or job_id = ‘AD_PRES’;
其中 job_id = ‘IT_PROT’ or job_id = ‘AD_VP’ or job_id = ‘AD_PRES’; 可以换成这一句话 job_id in(‘IT_PROT’,‘AD_VP’,‘AD_PRES’);
不可以写成 job_id in(‘IT_PROT’,'AD%’); - (4) is null
案例1:查询没有奖金的员工名和奖金率
=或<>不能用于判断null值
is null 或 is not null 可以判断 null 值
select
last_name,
commission_pct
from
employees
where
commission_pct = NULL; // 不能这么写,得换成commission_pct is NULL;
如果是查询有奖金的应该改成:commission_pct is not NULL; - select
last_name,
commission_pct
from
employees
where
salary is12000;
这个是错误的 is 现在只能和 null 搭配的
SQLyog里面的注释可以用 #
安全等于:
- 符号:<=>
案例1:查询没有奖金的员工名和奖金率
select
last_name,
commission_pct
from
employees
where
commission_pct <=> NULL;
案例2:查询工资为12000的员工信息
select
last_name,
salary
from
employees
where
salary <=> 12000; - is null 和 <=> 的区别
is null: 仅仅可以判断null值
<=>: 既可以判断null值,又可以判断普通的数值