SQL语句之条件查询–WHERE(where)

语法表示

select 
	查询列表
from
	表名
where
	筛选条件

筛选条件分类:

筛选方式运算符类型运算符
一,按条件表达式筛选条件运算符> 、< 、= 、!=(建议使用<> )、>=、 <=
二,按照逻辑表达式筛选(一般就是用于连接多个条件表达式)逻辑运算符&& 、 || 、 ! 、and、or
三,模糊查询模糊查询关键字like,between and,in ,is null

一、按条件表达式筛选

例:

select 
	* 
from 
	employees 
where 
	salary>12000;

目的:筛选出employees 表中薪水字段中,工资高于12000的。
例:

select 
	last_name,department 
from 
	employees 
where 
	department_id <>90;

目的:筛选出employees 表中,部门id不等于90的。

二、逻辑查询(一般就是用来连接上一小节介绍的多个条件表达式)

例:

select 
	last_name,department 
from 
	employees 
where 
	salary>=10000 and salary<=20000;

目的:筛选出employees 表中薪水字段中,工资高于10000,低于20000的。

例:

select 
	* 
from 
	employees 
where 
	not(department_id >= 90 and department_id <= 110) or salary > 15000;

目的:筛选出employees 表,部门编号不在90-110中的,或者是薪资高于15000的。

三、模糊查询

关键字1:like

在使用like关键字时,通常都会配合一些正则符号来使用:诸如%,_,escape等。

通配符1:% (通配符,表示多个字符)
例:

select 
	* 
from 
	employees 
where 
	last_name like '%a%';

目的:筛选出employees 表中,last_name字段中,含有a的。

通配符2:(通配符,表示单个字符,如果要表示两个,就两个
例:

select 
	last_name 
from 
	employees 
where 
	last_name like '__n_l%';

目的:筛选出employees 表中,last_name字段中,第三个字符为n,第五个字符为l的。

关键字3:escape(转义字符申明,只要通过这个字符,都可以申请为转义字符,所以后面的_才会被当做真正的下划线。)
例:

select 
	* 
from 
	employees 
where 
	last_name like '_$_%' escape '$';

目的:筛选出employees 表中,last_name字段中,第二个字段是_的。

关键字2:between and

例:

select 
	* 
from 
	employees 
where 
	employee_id between 100 and 120;

目的:筛选出employees 表中,employee_id 在100-120之间的。

关键字3:in(包含关键字,表示是否含有列表中的其中一项)

例:

 select 
 	last_name 
 from 
 	employees 
 where 
 	job_id in('IT_PROT','AD_VP','AD_PRES');

目的:筛选出employees 表中,job_id 是否属于(‘IT_PROT’,‘AD_VP’,‘AD_PRES’)中的一项,比or关键字要好用

关键字4:is null和is not null

例:

select 
	last_name,commission_pct 
from 
	employees
where 
	commission_pct IS NULL;

目的:筛选出employees 表中,奖金为0的人

例:

select 
	last_name,commission_pct 
from 
	employees 
where 
	commission_pct IS NOT NULL;

目的:筛选出employees 表中,奖金不为0的人

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐