1.数据库来源:Mysql 基础教程
2.数据库说明:
本文使用的数据库名称为 myemployees,其中有 8 张表,分别为 customers 表,departments 表,employees 表,job_grades 表,jobs 表,locations 表,orders 表,salespeople 表。
一、条件查询基本语法
select 查询列表 from 表名
where 筛选条件
二、条件查询筛选分类
1. 按条件表达式筛选
条件运算符:>,<,=,<>,>=,<=
2. 按逻辑表达式筛选
逻辑运算符:&&,||,!,and,or,not
&& 和 and:两个条件都为 true,结果为 true,反之为 false
|| 或 or: 只要有一个条件为 true,结果为 true,反之为 false
! 或 not: 如果连接的条件本身为 false,结果为 true,反之为 false
3. 按模糊查询筛选
like,between and,in,is null
like:
① 一般和通配符搭配使用
② % 表示任意多个字符,包含0个字符
③ _ 表示任意单个字符
between and:
① 可提高语句的简洁度
② 包含临界值
③ 两个临界值不能调换顺序
in:
① 判断某字段的值是否属于 in 列表中的某一项
② in 列表的值类型必须一致或兼容
③ in 列表中不支持通配符
三、条件查询相关案例(仅展示有限部分)
案例一:查询工资 > 12000的员工信息
select * from employees
where salary > 12000
案例二:查询部门编号不等于90号的员工名和部门编号
select last_name, department_id
from employees
where department_id <> 90
案例三:查询工资在 10000 到 20000 之间的有奖金的员工名、工资以及奖金
select last_name, salary, commission_pct
from employees
where salary between 10000 and 20000
and commission_pct is not null
案例四:查询部门编号不是在 90 到 110 之间,或者工资高于 15000 的员工信息
select * from employees
where department_id not between 90 and 110
or salary > 15000
案例五:查询员工名中包含字符 a,且部门号大于 50,有奖金的员工信息
select * from employees
where last_name like '%a%'
and department_id > 50
and commission_pct is not null
案例六:查询员工的工种编号是 IT_PROG、AD_VP、AD_PRES中的一个员工名和工种编号
select last_name, job_id
from employees
where job_id in('IT_PROT' ,'AD_VP','AD_PRES')