1.2从表中选取符合条件的数据
WHERE语句
当不需要取出全部数据,而是选取出满足“商品种类为衣服”“销售单价在1000日元以上”等某些条件的数据时,使用WHERE语句。
3.3 通过括号优先处理
如果要查找这样一个商品,该怎么处理?
“商品种类为办公用品”并且“登记日期是 2009 年 9 月 11 日或者 2009 年 9 月 20 日”
理想结果为“打孔器”,但当你输入以下信息时,会得到错误结果
-- 将查询条件原封不动地写入条件表达式,会得到错误结果
SELECT product_name, product_type, regist_date
FROM product
WHERE product_type = '办公用品'
AND regist_date = '2009-09-11'
OR regist_date = '2009-09-20';
错误的原因是是 AND 运算符优先于 OR 运算符,想要优先执行OR运算,可以使用括号:
-- 通过使用括号让OR运算符先于AND运算符执行
SELECT product_name, product_type, regist_date
FROM product
WHERE product_type = '办公用品'
AND ( regist_date = '2009-09-11'
OR regist_date = '2009-09-20');
练习题1
编写一条SQL语句,从product(商品)表中选取出“登记日期(regist在2009年4月28日之后”的商品,查询结果要包含product_name和regist_date两列。
select product_name,regist_data
from product
where regist_data> ' 2009.4.28 '
练习题2
请说出对product 表执行如下3条SELECT语句时的返回结果。
① 查询product表中purchase_price为null的所有数据
SELECT *
FROM product
WHERE purchase_price = NULL;
② 查询product表中purchase_price不为null的所有数据
SELECT *
FROM product
WHERE purchase_price <> NULL;
③ 查询product表中purchase_name不为null的所有数据
SELECT *
FROM product
WHERE product_name > NULL;
练习题3
代码清单2-22(2-2节)中的SELECT语句能够从product表中取出“销售单价(saleprice)比进货单价(purchase price)高出500日元以上”的商品。请写出两条可以得到相同结果的SELECT语句。执行结果如下所示。
product_name | sale_price | purchase_price
-------------+------------+------------
T恤衫 | 1000 | 500
运动T恤 | 4000 | 2800
高压锅 | 6800 | 5000
1.
select product_name , sale_price,purchase_price
from product
where salepirce>= purchase price + 500
2.
select product_name , sale_price,purchase_price
from product
where purchase price + 500 <=salepirce
练习题4
请写出一条SELECT语句,从product表中选取出满足“销售单价打九折之后利润高于100日元的办公用品和厨房用具”条件的记录。查询结果要包括product_name列、product_type列以及销售单价打九折之后的利润(别名设定为profit)。
提示:销售单价打九折,可以通过saleprice列的值乘以0.9获得,利润可以通过该值减去purchase_price列的值获得。
select product_name,product_type,(saleprice*0.9) - purchase_price as profit
from product
where profit >100
and ( product_type = '办公用品' )
or product_type ='厨房用具'))
练习题5
请指出下述SELECT语句中所有的语法错误。
SELECT product_id, SUM(product_name)
--本SELECT语句中存在错误。
FROM product
GROUP BY product_type
WHERE regist_date > '2009-09-01';
1.SUM函数不能用来计算product_name
2.group by不能在where前面
3.group by 字段 ( product_type )与select字段不同(product_id)
练习题6
请编写一条SELECT语句,求出销售单价(sale_price列)合计值大于进货单价(purchase_price列)合计值1.5倍的商品种类。执行结果如下所示。
product_type | sum | sum
-------------+------+------
衣服 | 5000 | 3300
办公用品 | 600 | 320
select product_type,sum(sale_price),sum(purchase_price)
from product
group by product_type
having sum(sale_pirce) >sum(purchase_price)*1.5
练习题7
此前我们曾经使用SELECT语句选取出了product(商品)表中的全部记录。当时我们使用了ORDERBY子句来指定排列顺序,但现在已经无法记起当时如何指定的了。请根据下列执行结果,思考ORDERBY子句的内容。
select *
from product
order by regist_date desc,sale_price;