条件查询
select
查询列表
from
表名
where
筛选条件;
分类:
1、按条件表达式筛选
简单条件运算符:> , < , = , !=(<>) , <= , >=
2、按逻辑表达式筛选
&& , || , !
and , or , not
&& 和 and :两个条件都为true,结果为true,反之为false
|| 和 or : 只要有一个条件为true,结果为true,反之为true
! 和 not : 如果连接条件本身为false,结果为true,反之为false
3、模糊查询
like
between and
in
is null
一、按条件表达式筛选
案例1:查询员工工资大于1200的员工信息
select
*
from
employees
where
salary>1200;
#select concat(first_name,' ',last_name) as name,salary from employees where salary>1200;
查询部门编号不等于90号的员工名和部门编号
select
concat(first_name,' ',last_name),department_id
from
employees
where
department_id!=90;
# 建议使用 <> 不使用 !=
二、按逻辑表达式筛选
案例1:查询工资在10000到20000之间的员工名、工资以及奖金
select
concat(first_name,' ',last_name) as name,salary,commission_pct
from
employees
where
salary>=10000 and salary <=20000;
案例2:查询部门编号在90到110之间,或工资高于15000的y员工信息
# 查询部门编号在90到110之间,或工资高于15000的y员工信息
select
concat(first_name,' ',last_name) as name,department_id,salary
from
employees
where
(department_id>90 and department_id<110) or salary>15000;
# 查询部门编号不是在90到110之间,或工资高于15000的y员工信息
select
concat(first_name,' ',last_name) as name,department_id,salary
from
employees
where
not(department_id>=90 and department_id<=110) or salary>15000;
#或者
select
concat(first_name,' ',last_name) as name,department_id,salary
from
employees
where
department_id<90 or department_id>110 or salary>15000;
三、模糊查询
like
between and
in
is null | is not null
1、like
特点:
1、一般和通配符搭配使用
% 任意 多个 字符,包含0个字符
_ 任意 单个 字符
【注】:若需要查询的词中包含特殊字符,则需要进行转义
1、 默认转移字符为 \
2、自定义转义字符,可以使用 escape 关键字
案例1:查询员工名中包含字符 a 的员工姓名。
select
concat(first_name,' ',last_name) as name
from
employees
where
last_name like '%a%' or first_name like '%a%';
案例2:查询员工名中,第三个字符为n,第5个字符为l 的员工名和工资。
select
last_name,salary
from
employees
where
last_name like '__n_l%';
查询员工民中第二个字符为 _ 的员工名
select
last_name
from
employees
where
last_name like '_\_%';
#或者自定义转义字符
select
last_name
from
employees
where
last_name like '_$_%' escape '$'; #指定 $ 为转义字符
2、between and
1、使用between and 可以提高语句的简洁度
2、包含临界值
3、两个临界值不能