MySQL 3つ以上のテーブルの結合

3つ以上のテーブルの結合

注文一覧に注文詳細と商品情報を一緒に出力します。

注文一覧 テーブル1(o) 

id user_id amount order_time
1 504 37500 2017-01-01 03:43:00
2 469 71200 2017-01-01 04:48:00
3 1 14900 2017-01-01 08:41:00
4 25 38900 2017-01-01 13:10:00
5 87 35200 2017-01-01 19:49:00

注文詳細 テーブル2(d)

id order_id product_id product_qty product_price
1 1 785 2 2700
2 1 718 1 9200
3 1 458 3 5500
4 1 427 2 3200
5 2 269 3 2800

商品情報 テーブル3(p)

id user_id amount
269 商品0269 2800
427 商品0427 3200
458 商品0458 5500
718 商品0718 9200
785 商品0785 2700

まず、inner join の構文を使って注文一覧・詳細情報・商品情報を内部結合します。

select
   *
from
   テーブル1 as o  /* テーブル1を oに置き換え */
inner join
   テーブル2 as d  /* テーブル2を dに置き換え */
on o.id = od.order_id
inner join
   テーブル3 as p  /* テーブル3を pに置き換え */
on d.product_id = p.id;

すると以下のように表示されます。

次にアスタリスク「*」を消して必要な部分だけを取り出し、必要に応じ名前をつけます。

select
   o.id order_id,  /* テーブル1のidorder_idと列名を付ける */
   o.user_id user_id, /* テーブル1のuser_iduser_idと列名を付ける */
   o.amount amount, /* テーブル1のamountamountと列名を付ける */
   o.order_time order_time, /* テーブル1のorder_timeorder_timeと列名を付ける */
   p.name product_name, /* テーブル3のnameproduct_nameと列名を付ける */
   d.product_qty qty, /*テーブル2のproduct_qtyqtyと列名を付ける */
   p.price product_price /*テーブル3のpriceproduct_priceと列名を付ける */
from
  テーブル1 o 
inner join
   テーブル2 d 
on o.id = d.order_id
inner join
   テーブル3 p 
on d.product_id = p.id;

すると以下のように

オーダーid・ユーザーid・注文金額・オーダー日時・商品名・販売個数・商品の単価

が出力されます。

4つのテーブルの結合

上記のデータの注文一覧のuser_id とユーザーテーブルのidを結合して名前を表示します。

注文一覧 テーブル1(o) 

id user_id amount order_time
1 504 37500 2017-01-01 03:43:00
2 469 71200 2017-01-01 04:48:00
3 1 14900 2017-01-01 08:41:00
4 25 38900 2017-01-01 13:10:00
5 87 35200 2017-01-01 19:49:00

ユーザー テーブル4(u)

id email last_name Fist_name gender
1 xxxxx 田中 xxxx 2
25 xxxxx 広島 xxxx 1
87 xxxxx 佐々木 xxxx 2
469 xxxxx 大和 xxxx 1
504 xxxxx 河田 xxxx 1

select
   o.id order_id,
   o.user_id user_id,
   u.last_name last_name, /*テーブル4のlast_namelast_nameと列名を付ける */ 
   u.first_name first_name, /*テーブル4のfirst_namefirst_nameと列名を付ける */
   o.amount amount,
   o.order_time order_time,
   p.name product_name,
   d.product_qty qty,
   p.price product_price
from
   テーブル1 o
inner join
   テーブル2 d
on o.id = d.order_id
inner join
   テーブル3 p
on d.product_id = p.id
inner join             /* 以下3行jnner構文でテーブル4を結合 */
   テーブル4 u         /* テーブル4をuに置き換え */
   on o.user_id = u.id; /* テーブル1のuseridとテーブル4のidを結合 */

すると以下のように表示されます。


この記事が役に立ったと思ったらポチッ!っと応援お願いします。

↓  ↓

にほんブログ村 IT技術ブログへ

独学で進まないときは!
↓   ↓
時間や場所に縛られず学習できるMySQL3選

スポンサーリンク
スポンサーリンク
SNSフォローボタン

フォローする

シェアする

  • このエントリーをはてなブックマークに追加
スポンサーリンク
スポンサーリンク