SQL之子查询(2)

案例1:

表OrderItems代表订单商品信息表,prod_id为产品id;Orders表代表订单表有cust_id代表顾客id和订单日期order_date

OrderItems表

prod_id order_num
BR01 a0001
BR01 a0002
BR02 a0003
BR02 a0013

Orders表

order_num cust_id order_date
a0001 cust10 2022-01-01 00:00:00
a0002 cust1 2022-01-01 00:01:00
a0003 cust1 2022-01-02 00:00:00
a0013 cust2 2022-01-01 00:20:00

【问题】

编写 SQL 语句,使用子查询来确定哪些订单(在 OrderItems 中)购买了 prod_id 为 "BR01" 的产品,然后从 Orders 表中返回每个产品对应的顾客 ID(cust_id)和订单日期(order_date),按订购日期对结果进行升序排序。

提示:这一次使用联结和简单的等联结语法。

--t1:
select
  cust_id,
  order_date
from
  Orders,
  (
    select
      order_num
    from
      OrderItems
    where
      prod_id = 'BR01'
  ) t
where
  Orders.order_num = t.order_num
order by
  order_date 


--t2:
select
  cust_id,
  order_date
from
  Orders
where
  order_num in (
    select
      order_num
    from
      OrderItems
    where
      prod_id = 'BR01'
  )
order by
  order_date 

--t3:
select
  cust_id,
  order_date
from
  Orders a
  left join OrderItems b on a.order_num = b.order_num
where
  prod_id = 'BR01'
order by
  order_date

【示例结果】

返回顾客id cust_id和定单日期order_date

cust_id order_date
cust10 2022-01-01 00:00:00
cust1 2022-01-01 00:01:00

你可能感兴趣的:(SQL,sql,数据库)