MySQL 条件查询详解

 更新时间:2023年05月29日 11:41:31   作者:wxl@  
这篇文章主要介绍了MySQL条件查询,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

条件查询

语法:

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

分类:

  • 按条件表达式筛选:条件运算符:> < = != >= <=
  • 按逻辑表达式筛选:逻辑运算符:&& || ! 或者:and or not
  • 模糊查询:like, between and, in, is null.

首先看看按条件表达式查询:

# 查询工资大于12000的员工:
select * from employees where salary > 12000;
# 部门编号不等于90的员工名和部门编号
select department_ID, sname from employees where department_ID != 90;

按逻辑表达式筛选:

# 查看工资在10000到20000之间的员工名和工资
select sname, salary from employees where 
salary >=10000 and salary <= 20000;
# 查看部门编号不是在90到110之间并且工资高于20000的员工信息
select * from employees where department_ID<90 or department_ID>110 
or salary > 20000;

模糊查询

like:

 # 查询员工名中包含字符'a'的员工信息
 # 这里注意,MySQL中不区分大小写,所以名字中如果有大写的A也是包含进去的
 select * from temp where sname like '%a%'; /* 字符型一定只能是单引号,
 因为字符a的前后可能还有其他的字符,所以这里要在a的前后加上%,表示通配符*/

总结一下like的特点:

一般和通配符配合使用
常见通配符?
% :任意多个字符,包含0个
_ :下划线,任意的单个字符

# 查询员工姓名中第三个字符是'a'第五个是'e'的员工信息:
select * from employees where name like '__a_e%';
# 查询员工姓名中第二个字符是_的员工信息:
select * from employees where name like '_\_%';# 在这种like关键字模糊查询中可以使用转义字符\...
# 如果不想使用\也可以使用escape语句
select * from employees where name like '_$_%' escape '$';

between and:(简化and)

select * from employees where
salary between 120 and 200;

特点:

  • 可以简化代码。
  • 包含两个临界值(闭区间)。
  • 不可以将两个临界值互换。

in(简化or):

# 查询员工工种编号是AD_UI, AD_YU中的一个的员工的姓名和工号
select sname, job_id from employees where 
job_id='AD_UI' or job_id='AD_YU';
# 使用in:
select sname, job_id from employees where
job_id in ('AD_UI', 'AD_YU');
# 特殊情况:如果将最后一句改成job_id in ('AD%');是否可行?
select sname, job_id from employees where
job_id in ('AD%');# 这是不可行的,因为通配符只能在like语句中使用

is null:

注意事项:
不可以使用“=”来判断值是否为空:
is 和null应该是连在一起用的,不能判断其他的如:is 200

select * from employees where
salary = null;  # 这是错误的表示方式
select * from employees where
salary is null;  # 这是正确的表示方式
select * from employees where 
salary is 2000;  # 会报错
select * from employees where
salary is not null;  # 判断不是空

安全等于 <=>

安全等于可以判断null也可以用来判断常量值
可读性不高,一眼看去无法判断是等于还是不等于

select * from employees where
salary <=> null;  # 判断为空
select * from employees where 
salary <=> 12000;  # 判断常数值

到此这篇关于MySQL 条件查询 的文章就介绍到这了,更多相关mysql条件查询 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

最新评论