常见的条件查询

简单查询

-- select 字段1,字段2,....from 表名
select name,class,age from students;

去重查询

-- 去重
-- select distinct 字段1,... from 表名
select distinct sex from students;

比较运算符

-- 比较运算符:>,<,>=,<=,=
-- 1、查询小乔的年龄
select age from students where name='小乔';
-- 2、查询20岁以下的学生
select * from students where age<20;
-- 3、查询家乡不在北京的学生
select * from students where hometown !='北京';

逻辑运算符

-- 逻辑运算符 and ,or ,not
-- 1、查询年龄小于20的女同学
select * from students where age<20 and sex='女';
-- 2、查询女学生或1班的学生
select * from students where sex='女' or class='1班';
-- 3、查询非天津的学生
select * from students where hometown != '天津';
select * from students where not hometown = '天津';

模糊查询

-- 模糊查询
-- 关键字:like
-- %:匹配多个任意字符
-- _:匹配一个任意字符
-- 例1:查询姓孙的学生
select * from students where name like '孙%';
-- 例2:查询姓孙且名字是一个字的学生
select * from students where name like '孙_';

范围查询

-- 范围查询
-- in 表示在一个非连续的范围内
-- 例:查询家乡是北京或上海或广东的学生
select * from students where hometown ='北京' or hometown ='上海' or hometown ='广东';
select * from students where hometown in ('北京','上海','广东');
--  between ... and ...表示在一个连续的范围内
-- 例:查询年龄为18至20的学生
select * from students where age between 18 and 20;
select * from students where age>=18 and age<=20;

空判断

-- 空判断
-- Mysql 中空表示null,与''(空)是不一样的。
-- 判断为空:is null
-- 例:查询没有填写身份证的学生
select * from students where card is null;
-- l 判断非空: is not null
-- 例:查询填写了身份证的学生
select * from students where card is not null;

排序

-- 排序
-- 语法格式:
-- select * from 表名 order by 字段名1 asc|desc, 字段名2 asc|desc,... 
-- 说明:
-- 将行数据按照字段1进行排序,如果某些字段1的值相同时,则按照字段2排序,
-- 默认按照列值从小到大排列,asc升序,desc降序
-- 例2:查询所有学生信息,按年龄从大到小排序,年龄相同时,再按学号从小到大排序
select * from students order by  age desc,studentNo ;

聚合函数

-- 使用聚合函数方便进行数据统计
-- 注意:聚合函数不能在 where 中使用
-- count():查询总记录数
-- max(字段名):查询最大值
-- min(字段名):查询最小值
-- avg(字段名):查询平均值
-- sum(字段名):查询总和
-- 例1:查询学生总数
select count(*) from students;
-- 例2:查询女生的最大年龄
select max(age) from students where sex='女';

分组查询

-- 分组查询
-- 按照字段分组,此字段相同的数据会被放到一个组中
-- 分组的目的是对每一组的数据进行统计(使用聚合函数)
-- select 字段1,字段2,聚合函数... from 表名 group by 字段1,字段2... having 条件
-- 例1:查询各种性别的人数
select sex,count(*) from students group by sex;
--  关键字having后面的条件运算符与where的相同
-- 例1:查询男生总人数
select sex ,count(*) from students group by sex having sex='男';

分页查询


-- 分页 用来获取一部分的数据或者用来分页
-- select * from 表名 limit start,count
-- 从start开始,获取count条数据
-- start索引从0开始
-- 例1:查询前3行学生信息
select * from students limit  0,3;

-- Limit典型应用场景是分页查询:
-- select * from students limit (n-1)*m, m
-- n表示显示第几页的数据
-- m表示每页显示多少条数据
-- (n-1)*m, m 是公式,并不是语法格式,不能直接写在SQL语句中

where和having的区别

-- having与where对比
-- ①where是对from后面指定的表进行数据筛选,属于对原始数据的筛选
-- ②having是对group by 的结果进行筛选
-- ③having后面的条件中可以用聚合函数,where后面不可以。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值