更多查询
带比较操作符
大于:>
小于:<
大于等于:>=
小于等于:<=
不等于:<>或者!=
示例:查询所有订单金额大于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;