MySQL基础操作学习(二)

这篇博客详细介绍了MySQL的基础查询操作,包括比较操作符、逻辑运算符、范围查询、模糊查询、空值判断,以及查询子句的使用,如排序、LIMIT、DISTINCT、聚合函数、分组和HAVING过滤。通过实例展示了如何有效地筛选和处理数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

更多查询

带比较操作符

大于:>
小于:<
大于等于:>=
小于等于:<=
不等于:<>或者!=
示例:查询所有订单金额大于200的订单

select * from orders where amt > 200

逻辑运算符

and:多个条件同时满足时输出
or:满足任意一个条件就输出
示例:
查询客户名称为"zs"且金额大于200的订单

select * from orders where cust_name = "zs" and amt > 200;

查询订单号为1或者2,金额大于200的订单

select * from orders where (order_id = 1 or order_id =2) and amt >200;

范围比较

(1)between……and……
示例:查找订单金额在200到300之间的订单

select * from orders where amt between 200 and 300;

(2)in / not in
示例:查找订单客户除了"David"的订单

select * from orders where cust_name not in ("David");

模糊查询

where 字段 like “通配符”
通配符1:下划线 " _",匹配单个字符
通配符2:百分号"%",匹配多个字符
示例:
查询所有客户姓名中以D开头的客户

select cust_name from orders where cust_name like "D%";

空值、非空判断

空值:is null
非空:is not null
示例:查询客户号码为空的订单

select * from orders where tel_no is null

查询子句

排序

order by 字段[asc/desc]
正序:asc 默认正序
倒序:desc
示例:按从大到小排列订单金额得到订单信息

select * from orders order by amt desc;

limit子句

限制显示数量
limit n;显示前n个
limit
示例:
(1)查询所有订单,只显示前2笔

select * from orders limit 2;

(2)查询所有订单,从第二笔开始,共显示5笔订单

select * from orders limit 2,5;

distinct 子句

去除重复数据

select distinct(要去重的字段)from 表名;

聚合函数

(1)求最大

  select max(字段名) from 表名;

(2)求最小

 select min(字段名) from 表名;

(3)求平均

select avg(字段名) from 表名;

(4)求和

select sum(字段名) from 表名;

(5)求数量

select count(*) from 表名;

分组

group by 需分组字段;
示例:
按照客户名称统计客户数量

select cust_name,count(*) 
from customer where cust_name like "A%" 
group by cust_name;

过滤

对分组进行过滤,通常和聚合函数搭配使用
group by 字段名 having 条件;
示例:
按照客户名称进行分类并过滤掉没有订单的客户姓名

select cust_name 
from customer group by cust_name 
having order_id is not null;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值