题解 | #确定哪些订单购买了 prod_id 为 BR01 的产品(二)#
确定哪些订单购买了 prod_id 为 BR01 的产品(二)
http://www.nowcoder.com/practice/999aa31a9a504c60baa088d90d82e64d
方法一:使用子查询
- 首先,能将
OrderItems表和Orders表关联起来的字段为order_num; - 根据题目要求,需要先使用子查询来查询
OrderItems,查询条件的字段为prod_id,查询的结果集为order_num字段的; - 之后外层查询,查询
Orders表,查询的条件为order_num字段,用order_num字段去匹配子查询的结果集; - 最后再排序。
select cust_id, order_date
from Orders
where order_num in (select order_num from OrderItems where prod_id = "BR01")
order by order_date;
方法二:使用2表连接
- 将
OrderItems表和Orders表连接成新表,连接条件的字段为order_num;
select o.cust_id as cust_id, o.order_date as order_date
from OrderItems oi join Orders o on oi.order_num=o.order_num
where oi.prod_id='BR01'
order by order_date;
- 从
group by字段开始,可以使用别名。

