0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

テーブルの結合(標準とOracle特有の比較)

Last updated at Posted at 2020-08-26

はじめに

テーブルの外部結合がいつもわからなくなるのでメモ。
特にレガシーシステムの改修を行っていたらOracle特有の書き方に出くわして、
どっちが左?どっちが右?となるので、標準的な書き方とOracle特有の書き方を列挙。

テーブル

テーブルは以下のように「animalsテーブル」と「categorysテーブル」を用意

animalsテーブル

id name category_id
1 柴犬 1
2 トイプードル 1
3 にわとり 3
4 へび 4
5 さんま 5

categorysテーブル

id category_name
1
2
3
5

内部結合

まずは普通に内部結合

標準の書き方

SELECT animals.id, animals.name, categorys.category_name
  FROM animals INNER JOIN categorys 
               ON animals.category_id = categorys.id;

別解

    SELECT animals.id, animals.name, categorys.category_name
      FROM animals, categorys
     WHERE animals.category_id = categorys.id;

結果

id name category_name
1 柴犬
2 トイプードル
3 にわとり
5 さんま

外部結合(左結合)

標準の書き方

SELECT animals.id, animals.name, categorys.category_name
  FROM animals LEFT OUTER JOIN categorys 
                    ON animals.category_id = categorys.id;

Oracle特有の書き方

SELECT animals.id, animals.name, categorys.category_name
  FROM animals, categorys 
 WHERE animals.category_id = categorys.id(+);

結果

id name category_name
1 柴犬
2 トイプードル
3 にわとり
4 へび NULL
5 さんま

Oracle特有の書き方の場合、
**(+)**をつける方が親に対してテーブルのデータが足りないという風に考えておく!
**(+)**をつけた方にNULLが入るみたいなイメージ

外部結合(右結合)

標準の書き方

SELECT animals.id, animals.name, categorys.category_name
  FROM animals RIGHT OUTER JOIN categorys 
                    ON animals.category_id = categorys.id;

Oracle特有の書き方

SELECT animals.id, animals.name, categorys.category_name
  FROM animals, categorys 
 WHERE animals.category_id(+) = categorys.id;

結果

id name category_name
1 柴犬
2 トイプードル
NULL NULL
3 にわとり
5 さんま
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?