LoginSignup
6
0

More than 3 years have passed since last update.

SQLのJOIN

Posted at

LRFT JOIN(= LEFT OUTER JOIN)

select * from tableA
left join tabelB on tableA.id = tableB.A_id
where tableB is null

tableAに(leftに)レコードがあればtabeBになくても取得対象となる。

RIGHT JOIN(= RGIHT OUTER JOIN)

select * from tableA
right join tabelB on tableA.id = tableB.A_id
where tableB is null

tableBに(rightに)レコードがあればtableAにレコードがなくても取得対象となる。
なのでこのwhere句は意味がない。

left joinright join は SQL分の位置が変わっただけ、
right joinleft join で書き換えることができる。(逆も書き換え可能)

INNER JOIN

select * from tableA
join tabelB on tableA.id = tableB.A_id
where tableB is null

where句関係なくそもそも tableAにもtableBにも存在するレコードしか取得対象とならない(なのでこのwhere句は意味がない)

JOINのアルゴリズム

[SQL実践入門]結合のアルゴリズム Nested Loops, Hash, Sort Merge - SIS Lab

  • Nested Loop Join(NLJ)
    • 1行ずつループして処理する
  • Hash Join
    • 一度に前件を読み込んで処理する
  • Sort Join
    • 全件をソートして上から順に比較する

MySqlはNLJしかサポートしていない。
PostgerSQLは3種類をサポートしている。

JOINの問題点

JOINの回数が増えると急激に重くなる

  • テーブルA、B、CをJOINした場合
    AとB、AとC、BとC

  • テーブルA、B、C、DをJOINした場合
    AとB、AとC、AとD、BとC、BとD、CとD

  • 100行と100行のJOIN
    10,000行のテーブルスキャン相当

  • 10,000行と10,000行のJOIN
    1,000,000,000行のテーブルスキャン相当

JOINを高速にするための工夫

参考

失敗から学ぶRDBの正しい歩き方 (Software Design plus) | 曽根 壮大 |本 | 通販 | Amazon

6
0
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
6
0