MySQL的DQL语言:2、条件查询

本文详细介绍了MySQL中的条件查询,包括按条件表达式筛选、逻辑表达式筛选、模糊查询(LIKE、BETWEEN AND、IN)以及IS NULL和安全等于<=>的用法,通过多个案例展示了如何查询特定条件的数据,如工资范围、特定字符匹配、空值判断等。
摘要由CSDN通过智能技术生成

条件查询

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、两个临界值不能
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值