LoginSignup
5
5

More than 5 years have passed since last update.

みんなの為のMySQLまとめ(4)

Last updated at Posted at 2015-02-07

参考
http://homepage2.nifty.com/sak/w_sak3/doc/sysbrd/mysql_09.htm

■単純結合

・次の例では、test2m の各レコードに testm の全レコードが結合される。
test2m のレコード数 x testm のレコード数の結果が問い合わされる。
テーブルtestmとtest2mをそれぞれ作成↓

create table testm (
  key1   char(8),
  data1  int8,
  data2  int8,
  data3  int8
) type=InnoDB;

insert into testm values ('a001', 1, 2, 3);
insert into testm values ('a011', 1, 2, 3);
insert into testm values ('b002', 10, 20, 30);
insert into testm values ('c003', 100, 200, 300);

create table test2m (
  key1   char(8),
  code1  char(8)
) type=InnoDB;

insert into test2m values ('abc01', 'a001');
insert into test2m values ('abc02', 'a011');
insert into test2m values ('abc03', 'z999');

select * from test2m, testm;
select * from test2m cross join testm;
kobito.1423323997.030812.png
 

■等価結合

・等価結合は、特定のキーで表を結合します。
条件のどちらかのデータが存在しない場合、結果セットには含まれません。
現実的には外部結合が一番使いやすいと思います。

select
test2m.key1,
code1,
data1,
data2,
data3
from test2m, testm
where test2m.code1 = testm.key1
;

・inner join を使用して、等価結合することもできます。(インナージョイン)

select
test2m.key1,
code1,
data1,
data2,
data3
from test2m inner join testm on test2m.code1 = testm.key1
;
kobito.1423324386.271575.png

・3 つ以上の結合を inner join で指定するには、次のようにする。

select
test2m.key1,
...
from (test2m inner join testm on test2m.code1 = testm.key1)
inner join test3m on test2m.code1 = test3m.key1
;

■非等価結合

・非常に時間のかかる結合ですが、必要な場面があるかもしれない。
なにがしかの範囲条件で結合する場合に使います。

select
test2m.key1,
code1,
data1,
data2,
data3
from test2m, testm
where test2m.code1 like concat(substring(testm.key1, 1, 2), '%')
;
kobito.1423324686.891980.png
 

■外部結合(外結合、行結合、行連結、テーブル結合、外部接合)

・外部結合は、一番よく使用します。
一方の条件に対するデータが存在しなかった場合でも片方のデータを結果セ
ットに含める指定ができます。
(左結合、右結合、複数テーブル問い合わせ、複数テーブル参照)
(複数問い合わせ、複合テーブル参照、レフトジョイン、ライトジョイン)

select
test2m.key1,
code1,
data1,
data2,
data3
from test2m left join testm on test2m.code1 = testm.key1
;

・right join は、left join の逆で、次のようにする。

select
test2m.key1,
code1,
data1,
data2,
data3
from test2m right join testm on test2m.code1 = testm.key1
;
kobito.1423325091.920580.png

・三つ以上の表を結合することもできます。(3 テーブル結合)

select
test2m.key1,
...
from (test2m left join testm on test2m.code1 = testm.key1)
left join test3m on test2m.code1 = test3m.key1
;

・複数の表を結合すると修飾が難解になりがちなので、テーブル別名を使うと
良いです。

select
a.key1 as key1,
code1,
data1,
data2,
data3
from test2m a left join testm b on a.code1 = b.key1
;

** 外部結合を明示するために left join を left outer join、right join
を right outer join と書くこともできる。
(アウタージョイン、レフトアウタージョイン、ライトアウタージョイン)

select
a.key1 as key1,
code1,
data1,
data2,
data3
from test2m a left outer join testm b on a.code1 = b.key1
;
kobito.1423325445.580918.png

5
5
0

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
5
5