ケース 1:
OrderItems テーブルは注文製品情報テーブルを表し、prod_id は製品 ID です。Orders テーブルは、顧客 ID と注文日 order_date を表す cust_id を持つ注文テーブルを表します。
OrderItems テーブル
製品ID | 注文番号 |
BR01 | a0001 |
BR01 | a0002 |
BR02 | a0003 |
BR02 | a0013 |
注文テーブル
注文番号 | cust_id | 注文日 |
a0001 | コスト10 | 2022-01-01 00:00:00 |
a0002 | カス1 | 2022-01-01 00:01:00 |
a0003 | カス1 | 2022-01-02 00:00:00 |
a0013 | カス2 | 2022-01-01 00:20:00 |
【質問】
サブクエリを使用して、prod_id "BR01" の製品を購入した注文 (OrderItems 内の) を特定し、Orders テーブルから各製品の顧客 ID (cust_id) と注文日 (order_date) を注文別に返す SQL ステートメントを作成します。日付は結果を昇順に並べ替えます。
ヒント: 今回は結合と単純な等結合構文を使用します。
--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 | 注文日 |
コスト10 | 2022-01-01 00:00:00 |
カス1 | 2022-01-01 00:01:00 |