在SQL查询中的常见语句顺序是
selectfromwhereorder by使用的数据是《SQL必知必会》书中的栗子。五个表分别是:
Vendors:存储销售产品的供应商信息,每个供应商对应一条记录Products:产品目录,每行对应一个产品Customers:存储顾客信息的表Orders:存储顾客订单(订单日期,订单顾客ID)OrderItems:订单的详细信息,每个订单中每个物品对应一行数据
排序查询是通过order by关键字实现,位置一定是select语句的最后一个子句
-- 单个排序字段
select prod_name
from Products
order by prod_name; -- 按照名字的字母进行排序,最后的语句
-- 多个排序字段
select prod_id, prod_price, prod_name
from Products
order by prod_price, prod_name; -- 多个字段按照顺序查询-- 相对位置排序(和上面的可以混合使用)
select prod_id, prod_price, prod_name
from Products
order by 2, 3; -- 2:prod_price,3:prod_name排序默认是升序asc,可以改成降序desc
select prod_id, prod_price, prod_name
from Products
order by prod_price desc, prod_name; -- 先对prod_price降序,再对prod_name升序过滤查询的关键字是where。order by 语句必须在where语句之后使用。两个特殊的操作符:
<>和!=等价,都是不等于!<和>=等价select prod_name, prod_price
from Porducts
where prod_price < 10;
where prod_price != 20;
where prod_price between 10 and 20;通过IS NULL实现
select prod_name, prod_price
from Porducts
where prod_price is null;在查询的过程中可以同时使用and和or
and优先级在前()优先级最高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操作符更快select语句select prod_name, prod_price
from Porducts
where vend_id in ('BRS01','DLL01') --等价于or语句
order by prod_name;一个not操作符号的栗子
select prod_name
from Products
where not vend_id = 'DLL01' -- 等价于vend_id <> 'DLL01'
order by prod_name;