1、案例
案例1:
OrderItems表示订单商品表,含有字段订单号:order_num、订单价格:item_price;Orders表代表订单信息表,含有顾客id:cust_id和订单号:order_num
OrderItems表
order_num | item_price |
a1 | 10 |
a2 | 1 |
a2 | 1 |
a4 | 2 |
a5 | 5 |
a2 | 1 |
a7 | 7 |
Orders表
order_num | cust_id |
a1 | cust10 |
a2 | cust1 |
a2 | cust1 |
a4 | cust2 |
a5 | cust5 |
a2 | cust1 |
a7 | cust7 |
【问题】使用子查询,返回购买价格为 10 美元或以上产品的顾客列表,结果无需排序。
注意:你需要使用 OrderItems 表查找匹配的订单号(order_num),然后使用Order 表检索这些匹配订单的顾客 ID(cust_id)。
--T1:
select cust_id
from Orders
left join OrderItems
on OrderItems.order_num = Orders.order_num
where item_price >= '10'
--PS:同一顾客可能会多次购买十美元及以上的商品,故需要用DISTINCT去重
--T2:
SELECT DISTINCT cust_id
FROM Orders
WHERE order_num IN (
SELECT order_num
FROM OrderItems
WHERE item_price >= '10')
【示例结果】返回顾客id cust_id