顾名思义, 条件查询就是使用where字句 , 将满足条件的数据筛选出来

语法 :

select < 结果 > from < 表名 > where < 条件 >

这里我们以t_user表为例

-- 查询性别为男的信息
select * from t_user where sex='男'
-- 查询性别不为男的信息
select * from t_user where not sex='男'
-- 查询性别为男并且年龄为20的信息
select * from t_user where sex='男' and age=20
-- 查询性别为男或者年龄为20的信息
select * from t_user where sex='男' or age=20

模糊查询

like

是否匹配于一个模式 一般和通配符搭配使用,可以判断字符型数值或数值型.    

通配符: % 任意多个字符,包含 0 个字符 _ 任意单个字符

我们知道, 在实际查询中, 往往我们只需要大致的信息, 就能查到我们需要的结果(例如淘宝搜索商品等) , 而这就需要到了模糊查询 ,例 :

-- _下划线一次匹配一个字符
-- %一次可以匹配0个或者多个字符
select * from t_user where name like '_李_'
select * from t_user where name like 'b__'
select * from t_user where name like 'b%'

上述第三条sql查询结果如下 : 

between and 两者之间 , 包含临界值;

in 判断某字段的值是否属于 in 列表中的某一项

is null (为空的)或 is not null (不为空的)

-- 查询体重在100和130之间的信息,包括100和130
select * from t_user where weight between 100 and 130
-- 查询体重是100或者110的信息
select * from t_user where weight in(100,110)
-- 查询生日为null或者不为null的信息
select * from t_user where birthday is null
select * from t_user where birthday is not null

这里需要注意, 我们如果要用null 来作为where的查询条件时 ,是不能写成下面这样

— select * from t_user where birthday=null

这样是查询不到结果的, 这里我们需要使用 is null

union

使用 union 或者 union all 会把两条sql语句的查询结果合并

当使用union 时,mysql 会把结果集中重复的记录删掉,而使用union all , mysql 会把所有的记录返回,且效率高于union 。

select * from t_user where age=20 
union 
select * from t_user where sex='男'

查询结果 : 

select * from t_user where age=20 
union all
select * from t_user where sex='男'

 查询结果 : 

排序 

查询结果排序 , 使用 order by 子句排序 order by 排序列 asc/desc

asc 代表的是升序, desc 代表的是降序,如果不写,默认是升序

order by 子句中可以支持单个字段、多个字段、表达式、函数、别名

-- 按体重升序排列
select * from t_user order by weight asc
-- 按体重降序排列
select * from t_user order by weight desc
-- 如果体重相等,就按照学号来排,升序
select * from t_user order by weight asc, number asc

数量限制

limit 子句:对查询的显示结果限制数目 (sql 语句最末尾位置 )

在实际查询中, 数据库内会存放大量的数据, 所以我们会对查询的数量进行控制,这时就需要limit

-- 从第一条数据开始查询2条数据(不包括第一条数据)
select * from t_user limit 1,2

limit  后第一位数字是指: 开始查询的位置

第二位数字是指: 查询的数据条数

分组

group by 子句 : 对查询的信息分组

having 子句 : 对分组后的结果集再进行筛选

-- 通过sex分组
-- 这里select后跟的必须是group by后的字段或者分组函数
select sex,avg(weight) from t_user group by sex
select sex,avg(weight) from t_user group by sex having sex='女'

这里需要注意的是: 

查询列表比较特殊,要求是分组函数和group by后出现的字段 

分组前筛选 原始表    group by 子句的前面         where

分组后筛选 分组后的结果集 group by 的后面    having

where 是分组前筛选, having是分组后筛选

综合

在实际的开发过程中,这些字句都是连在一起使用的,并且有着一定的位置, 位置不对就会报错,例:

select sex,avg (weight) w
from
  t_user
where sex = '男'
group by sex
having sex = '男'
order by w asc
limit 0, 1

子句的顺序是有一定要求的

查询结果 : 

到此这篇关于mysql条件查询语句常用操作全面汇总的文章就介绍到这了,更多相关mysql条件查询内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!