语法:
select
查询列表
from
表名
where
筛选条件;
分类:
一、按条件表达式筛选
条件运算符:> < = <> <= >=
二、按逻辑表达式筛选
逻辑运算符:用于连接条件表达式
&& || !
and or not
三、模糊查询
like
between and
in
is null
USE myemployees
1.按条件表达式筛选
案例1:查询工资>12000的员工信息
SELECT
*
FROM
employees
WHERE
salary>12000;
案例2:查询部门编号不等于90的员工名和部门编号
SELECT
last_name,`department_id`
FROM
employees
WHERE
`department_id` <> 90;
2.按逻辑表达式筛选
案例1:查询工资在10000到20000之间的员工名、工资以及奖金
SELECT
last_name,salary,commission_pct
FROM
employees
WHERE
salary <=20000
AND
salary>=10000;
案例2:查询部门编号不是在90到110之间,或者工资高于15000的员工信息
SELECT
*
FROM
employees
WHERE
NOT (`department_id` >= 90 AND `department_id` <= 110)
OR salary >= 150000
3.模糊查询
like
特点:
一般和通配符搭配使用:
通配符:
% 任意多个字符(包含0个字符)
_ 任意单个字符
\ 转义符
between and
in
is null is not null
1.like
也可以模糊查询数字
案例1.查询员工名中包含字符a的员工信息
SELECT
*
FROM
`employees`
WHERE
`last_name` LIKE '%a%';
案例2:查询员工名中第三个字符为e,第五个字符为a的员工名和工资
SELECT
last_name,
salary
FROM
employees
WHERE
last_name LIKE '__n_l%';
案例3:查询员工名中第二个字符为_的员工名
SELECT
last_name
FROM
employees
WHERE
last_name LIKE '_$_%' ESCAPE '$';#escape 定义转义符号
2.between and
使用between and 可以提高代码简洁度
包含左右临界值
左右临界值不可以颠倒顺序
实例1:查询员工编号在100到120之间的员工信息
SELECT
*
FROM
employees
WHERE
employee_id >= 100 AND employee_id <= 120;
#---------------------------------------------
SELECT
*
FROM
employees
WHERE
employee_id BETWEEN 100 AND 120;
3.in
含义:判断某字段的值是否属于in列表中的一项
特点:
使用in提高语句简洁度
in列表的值类型必须一致或兼容
不支持通配符
案例:查询员工的工种编号是 IT_PROG、AD_VP、AD_PRES中的一个员工和工种编号
SELECT
last_name,
job_id
FROM
employees
WHERE
job_id = 'IT_PROG' OR job_id = 'AD_VP' OR job_id = 'AD_PRES');
#------------------------------------------
SELECT
last_name,
job_id
FROM
employees
WHERE
job_id IN ('IT_PROG','AD_VP','AD_PRES');
4. is null
= 或 <> 不能用于判断null值
is null 或 is not null 可以判断null值
案例1:查询没有奖金的员工名和奖金率
SELECT
first_name,
commission_pct
FROM
employees
WHERE
commission_pct IS NULL;
案例2:查询有奖金的员工名和奖金率
SELECT
first_name,
commission_pct
FROM
employees
WHERE
commission_pct IS NOT NULL;
#-------以下为错误--------
SELECT
first_name,
commission_pct
FROM
employees
WHERE
salary IS 12000;
安全等于 <=>
可读性较差
案例1:查询没有奖金的员工名和奖金率
SELECT
first_name,
commission_pct
FROM
employees
WHERE
commission_pct <=> NULL;
案例2:查询工资为12000的员工信息
SELECT
last_name,
salary
FROM
employees
WHERE
salary <=> 12000;
--is null vs <=>------------------
/*
‘a’ is null vs ‘a’ <=> null
is null:仅仅可以判断null,可读性较高
<=>:既可以判断null,又可以判断普通的数值,可读性较低
*/
-----------练习-------------------
- 查询员工号为176的员工的姓名和部门号和年薪
SELECT
LAST_name,
`department_id`,
salary * 12 * (1+IFNULL(`commission_pct`,0)) AS 年薪
FROM
employees
WHERE
`employee_id` = 176;