Fork me on GitHub

MySQL学习8_排序与过滤

常见语句顺序

SQL查询中的常见语句顺序是

  • select
  • from
  • where
  • order by

使用的数据是《SQL必知必会》书中的栗子。五个表分别是:

  • Vendors:存储销售产品的供应商信息,每个供应商对应一条记录
  • Products:产品目录,每行对应一个产品
  • Customers:存储顾客信息的表
  • Orders:存储顾客订单(订单日期,订单顾客ID)
  • OrderItems:订单的详细信息,每个订单中每个物品对应一行数据

排序

排序查询是通过order by关键字实现,位置一定是select语句的最后一个子句

  • 单个字段直接排序
  • 多个字段:按照指定的字段顺序进行排序,仅仅只有前面的字段有相同值,才会对后面的字段进行排序
  • 按照列的相对位置进行排序

直接按照字段排序

1
2
3
4
5
6
7
8
9
-- 单个排序字段
select prod_name
from Products
order by prod_name; -- 按照名字的字母进行排序,最后的语句

-- 多个排序字段
select prod_id, prod_price, prod_name
from Products
order by prod_price, prod_name; -- 多个字段按照顺序查询

列的位置排序

1
2
3
4
-- 相对位置排序(和上面的可以混合使用)
select prod_id, prod_price, prod_name
from Products
order by 2, 3; -- 2:prod_price,3:prod_name

指定排序方向

排序默认是升序asc,可以改成降序desc

1
2
3
select prod_id, prod_price, prod_name
from Products
order by prod_price desc, prod_name; -- 先对prod_price降序,再对prod_name升序

过滤

过滤查询的关键字是whereorder by 语句必须在where语句之后使用。两个特殊的操作符:

  • <>!=等价,都是不等于
  • !<>=等价

查询范围值

1
2
3
4
5
select prod_name, prod_price 
from Porducts
where prod_price < 10;
where prod_price != 20;
where prod_price between 10 and 20;

空值查询

通过IS NULL实现

1
2
3
select prod_name, prod_price 
from Porducts
where prod_price is null;

多个条件

在查询的过程中可以同时使用andor

  • and优先级在前
  • ()优先级最高
1
2
3
4
5
6
select prod_name, prod_price 
from Porducts
where prod_price < 10 and vend_id = 'DLL01' -- and
where vend_id = 'BRS01' or vend_id = 'DLL01' -- or
where (vend_id = 'BRS01' or vend_id = 'DLL01') -- 加上()保证先执行
and prod_price >= 10; -- and优先级在前

in操作符

in取的是逗号分隔,括号里面的值,主要特点是

  • 语法清晰、更加直观
  • or操作符更快
  • 在in操作符中可以包含其他的select语句
1
2
3
4
select prod_name, prod_price 
from Porducts
where vend_id in ('BRS01','DLL01') --等价于or语句
order by prod_name;

一个not操作符号的栗子

1
2
3
4
select prod_name
from Products
where not vend_id = 'DLL01' -- 等价于vend_id <> 'DLL01'
order by prod_name;

本文标题:MySQL学习8_排序与过滤

发布时间:2019年10月04日 - 16:10

原始链接:http://www.renpeter.cn/2019/10/04/MySQL%E5%AD%A6%E4%B9%A08-%E6%8E%92%E5%BA%8F%E4%B8%8E%E8%BF%87%E6%BB%A4.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Coffee or Tea