LoginSignup
64
64

More than 5 years have passed since last update.

MySQLで異なるDBに存在するテーブルを結合して表示する方法

Last updated at Posted at 2016-06-27

前提

例えばdb_Aというデータベス内に、user_entryテーブルとusersテーブルがあるとします。

user_entry

id user_id created_at
1 3 2016-06-07 13:11:53
2 3 2016-06-09 12:04:02
3 1 2016-06-13 17:41:30
4 2 2016-06-13 18:56:00
5 3 2016-06-17 11:14:36

users

id email name
1 abc@gmail.com taro
2 def@gmail.com hanako
3 ghi@gmail.com takashi
4 jkl@gmail.com yumi
5 mno@gmail.com hiroshi

ここで、user_entryテーブルのuser_idをキーカラムとして、usersテーブルの内容を結合して表示させる場合、

select user_entry.id, user_entry.created_at, users.email, users.name 
from user_entry left join users on user_entry.user_id = users.id;

とすれば、

id created_at email name
1 2016-06-07 13:11:53 ghi@gmail.com takashi
2 2016-06-09 12:04:02 ghi@gmail.com takashi
3 2016-06-13 17:41:30 abc@gmail.com taro
4 2016-06-13 18:56:00 def@gmail.com hanako
5 2016-06-17 11:14:36 ghi@gmail.com takashi

このように期待どうりの結果が得られると思います。

しかし、

本題

もしも上記の例で、usersテーブルが別のデータベース(db_B)に存在する場合はどうでしょうか。具体的には、以下のような構成です。

db_A -> user_entry

id user_id created_at
1 3 2016-06-07 13:11:53
2 3 2016-06-09 12:04:02
3 1 2016-06-13 17:41:30
4 2 2016-06-13 18:56:00
5 3 2016-06-17 11:14:36

db_B -> users

id email name
1 abc@gmail.com taro
2 def@gmail.com hanako
3 ghi@gmail.com takashi
4 jkl@gmail.com yumi
5 mno@gmail.com hiroshi

このように、異なるデータベース間の結合は難しいのかなーと思っていたのですが、案外簡単でした。以下のような形で結合できるようです。

select db_A.user_entry.id, db_A.user_entry.created_at, db_B.users.email, db_B.users.name
from db_A.user_entry
left join db_B.users
on db_A.user_entry.user_id = db_B.users.id;

ただこれだと非常に見づらいので、以下のようにテーブルに別名を指定するのが良いかと思います。

select x.id, x.created_at, y.email, y.name
from db_A.user_entry as x
left join db_B.users as y
on x.user_id = y.id;
64
64
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
64
64