読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
予約の表と明細の表を結んで、名前と商品IDを並べます。
SELECT r.id, r.name, i.product_id, i.quantity
FROM reservations AS r
JOIN reservation_items AS i ON i.reservation_id = r.id
ORDER BY r.id, i.product_id;
id | name | product_id | quantity
--------+------+------------+----------
R-0001 | 田中 | p001 | 1
R-0001 | 田中 | p002 | 2
R-0002 | 鈴木 | p004 | 3
R-0003 | 高橋 | p003 | 4
R-0003 | 高橋 | p005 | 2
(5 rows)
| 部分 | 意味 |
|---|---|
FROM reservations AS r | 予約の表に r という短い名前を付ける |
JOIN reservation_items AS i | 明細の表を結び、i という短い名前を付ける |
ON i.reservation_id = r.id | 結ぶ条件。明細の予約IDと、予約のIDが等しい行どうしを結ぶ |
r.name、i.quantity | どちらの表の列かを、短い名前と . で示す |
ON の条件に合う行の組だけが、結果に残ります。このような結合を、内部結合(INNER JOIN)と呼びます。JOIN とだけ書くと、内部結合になります。
ON を書き忘れて FROM reservations JOIN reservation_items; とすると、syntax error at or near ";" になります。JOIN には結ぶ条件が必要です。
6 / 20