常见语句顺序
在SQL
查询中的常见语句顺序是
select
from
where
order by
使用的数据是《SQL
必知必会》书中的栗子。五个表分别是:
Vendors
:存储销售产品的供应商信息,每个供应商对应一条记录Products
:产品目录,每行对应一个产品Customers
:存储顾客信息的表Orders
:存储顾客订单(订单日期,订单顾客ID)OrderItems
:订单的详细信息,每个订单中每个物品对应一行数据
排序
排序查询是通过order by
关键字实现,位置一定是select语句的最后一个子句
- 单个字段直接排序
- 多个字段:按照指定的字段顺序进行排序,仅仅只有前面的字段有相同值,才会对后面的字段进行排序
- 按照列的相对位置进行排序
直接按照字段排序
1 |
|
列的位置排序
1 |
-- 相对位置排序(和上面的可以混合使用) |
指定排序方向
排序默认是升序asc
,可以改成降序desc
1 |
select prod_id, prod_price, prod_name |
过滤
过滤查询的关键字是where
。order by
语句必须在where
语句之后使用。两个特殊的操作符:
<>
和!=
等价,都是不等于!<
和>=
等价
查询范围值
1 |
select prod_name, prod_price |
空值查询
通过IS NULL
实现
1 |
select prod_name, prod_price |
多个条件
在查询的过程中可以同时使用and
和or
and
优先级在前()
优先级最高
1 |
select prod_name, prod_price |
in
操作符
in
取的是逗号分隔,括号里面的值,主要特点是
- 语法清晰、更加直观
- 比
or
操作符更快 - 在in操作符中可以包含其他的
select
语句
1 |
select prod_name, prod_price |
一个not操作符号的栗子
1 |
select prod_name |
近期评论