by shigemk2

当面は技術的なことしか書かない

INNER JOIN

内部結合(INNER JOIN句) - テーブルの結合 - SQLite入門

INNER JOIN(内部結合)はそれぞれのテーブルの指定した列の値が一致するデータだけを取得する。

たとえば、以下のようなテーブルがあったとする。

hoge1

user_id type name
1 MH engagesr1
2 MH engagesr2
3 HM ATOLLV
4 MH engagesr4
5 AB Zwauth
6 AB Zwarth
7 AB Wryneck
8 AB Leprechaun
9 AB Dumbine
10 AB Sirbine
11 AB Billbine
12 WM Zabungle
13 WM Walker-Gallia
14 KMF Gawain
15 TA Raiden
16 HM AshRaTemple

hoge2

id custom_id name
1 4 delta
2 6 zeta
3 9 iota
4 13 nu
5 14 xi

hoge3

id member_id name
1 1 Akaishi
2 10 Adachi
3 8 Amagi
4 7 Kuroishi
5 16 Kita
6 4 Ibuki
7 14 Miyaura
8 13 Shirane

INNER JOINを使ってSELECT文を発行してみる。
(書き方はLEFT JOINとかと変わらない)

mysql > select * from hoge1 inner join hoge2 on hoge1.user_id = hoge2.custom_id;

結果

user_id type name id custom_id name
4 MH engagesr4 1 4 delta
6 AB Zwarth 2 6 zeta
9 AB Dumbine 3 9 iota
13 WM Walker-Gallia 4 13 nu
14 KMF Gawain 5 14 xi

複数のテーブルをINNER JOINする。

mysql > select * from hoge1 inner join hoge2 on hoge1.user_id = hoge2.custom_id inner join hoge3 on hoge1.user_id = hoge3.member_id;

結果

user_id type name id custom_id name id member_id name
4 MH engagesr4 1 4 delta 6 4 Ibuki
14 KMF Gawain 5 14 xi 7 14 Miyaura
13 WM Walker-Gallia 4 13 nu 8 13 Shirane

ちなみに、LEFT JOINだと、一致していないものも検出される。

mysql > select * from hoge1 left join hoge2 on hoge1.user_id = hoge2.custom_id left join hoge3 on hoge1.user_id = hoge3.member_id;

結果

user_id type name id custom_id name id member_id name
1 MH engagesr1 NULL NULL NULL 1 1 Akaishi
2 MH engagesr2 NULL NULL NULL NULL NULL NULL
3 HM ATOLLV NULL NULL NULL NULL NULL NULL
4 MH engagesr4 1 4 delta 6 4 Ibuki
5 AB Zwauth NULL NULL NULL NULL NULL NULL
6 AB Zwarth 2 6 zeta NULL NULL NULL
7 AB Wryneck NULL NULL NULL 4 7 Kuroishi
8 AB Leprechaun NULL NULL NULL 3 8 Amagi
9 AB Dumbine 3 9 iota NULL NULL NULL
10 AB Sirbine NULL NULL NULL 2 10 Adachi
11 AB Billbine NULL NULL NULL NULL NULL NULL
12 WM Zabungle NULL NULL NULL NULL NULL NULL
13 WM Walker-Gallia 4 13 nu 8 13 Shirane
14 KMF Gawain 5 14 xi 7 14 Miyaura
15 TA Raiden NULL NULL NULL NULL NULL NULL
16 HM AshRaTemple NULL NULL NULL 5 16 Kita