4
6

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.

SQL文チートシート ~複数テーブル結合~

Posted at

自分用のSQLチートシートです。

  • Inner Joins
  • Left Joins

使用するテーブル

paper_magazinテーブルスキーマ

name type
id INTEGER
name TEXT
email TEXT

paper_magazinテーブルデータ

id name email
1 James james@email.com
2 Matt matt@email.com
3 Erin erin@email.com
4 Chris chris@email.com
5 Zan zan@email.com

online_magazinテーブルスキーマ

name type
id INTEGER
name TEXT
email TEXT

online_magazinテーブルデータ

| id | name | email |
| :---: | :---: | :---: | :---: | :---: |
| 1 | James |james@email.com |
| 2 | Matt | matt@email.com |
| 3 | Erin | erin@email.com |
| 6 | Jason | jason@email.com |
| 7 | Curry | curry@email.com |

Inner Joins

JOIN(inner joinと呼ばれている)を使って2つのテーブルを結合する場合はONの条件に合う結果だけが得られます。

magazine.sql
SELECT *
FROM paper_magazine
JOIN online_magazine
  ON paper_magazine.id = online_magazine.id;

SQL結果

| id | name | email | id | name | email |
| :---: | :---: | :---: | :---: | :---: | :---: | :---: |
| 1 | James |james@email.com | 1 | James |james@email.com |
| 2 | Matt | matt@email.com | 2 | Matt | matt@email.com |
| 3 | Erin | erin@email.com | 3 | Erin | erin@email.com |

Left Joins

LEFT JOINONの条件に合わないものも含めて結合されるテーブルの全ての行を残します。

magazine.sql
SELECT *
FROM paper_magazine
LEFT JOIN online_magazine
  ON paper_magazine.id = online_magazine.id;

SQL結果

id name email id name email
1 James james@email.com 1 James james@email.com
2 Matt matt@email.com 2 Matt matt@email.com
3 Erin erin@email.com 3 Erin erin@email.com
4 Chris chris@email.com NULL NULL NULL
5 Zan zan@email.com NULL NULL NULL

その他のチートシート

SQL文チートシート①
SQL文チートシート②

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?