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 1 year has passed since last update.

SQL JOINについて

0
Posted at

テーブル結合時のJOIN句について

JOINを使ってテーブル結合を行いデータを取得していますが、INNSER JOIN OUTER JOIN LEFT JOINなど、結合方法は色々ありますが、正しく使い分けられている自信がなかったので、改めて自身の備忘として残します。

INNER JOIN - 内部結合

例えば2つのテーブルを結合するクエリを作成する場合を仮定。
brandsテーブル、itemsテーブル
itemsテーブルにはbrand_idというカラムがあり、brands_idはbrands.idとの結合キーとします。

SELECT 
    items.brand_id, 
    items.name AS item_name, 
    brands.name AS brand_name 
FROM items
    INNER JOIN brands ON
        items.brand_id = brands.id;

上記のクエリで、内部結合でテーブル同士のデータを取得できます。
INNER JOINは、両テーブルの共に存在する情報だけを取得します。

OUTER JOIN - 外部結合

基本的な使い方は内部結合と同様です。
異なる点は結果のみ。
外部結合の場合は、片方のテーブルの値が全て出力されます。

SELECT 
    items.brand_id, 
    items.name AS item_name, 
    brands.name AS brand_name 
FROM items
    OUTER JOIN brands ON
        items.brand_id = brands.id;

その片方とは、JOINしたテーブルの情報です。
指定した元テーブルにはない情報を結果に持ってくる
のでOUTER JOIN(外部結合)ということになります。

指定にはLEFT RIGHTと指定ができ、私自身よく使う、よく見るのはLEFTです。
結合するテーブルを指定することはあまりないですが、それは状況んなどによって変わるかもしれません。

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?