0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SQLの基本(結合編)

Posted at

SQLの結合

SQLの結合というと「INNER JOIN」と「LEFT JOIN」ばかり使っていますが、「FULL JOIN」を使う機会があったのでEXISTSと合わせて図で表してみました。

table_a
code *
101
102
103
201
202
203
 
table_b
code *
201
202
203
204
205
206

内部結合

INNER JOIN

SELECT * 
  FROM table_a
 INNER JOIN table_b
         ON table_b.code = table_a.code

INNER_JOIN.png

table_a.code table_a.* table_b.code table_b.*
201 201
202 202
203 203

外部結合

LEFT JOIN

SELECT * 
  FROM table_a
  LEFT JOIN table_b
         ON table_b.code = table_a.code

LEFT_JOIN.png

table_a.code table_a.* table_b.code table_b.*
101 NULL NULL
102 NULL NULL
103 NULL NULL
201 201
202 202
203 203

RIGHT JOIN

SELECT * 
  FROM table_a
 RIGHT JOIN table_b
         ON table_b.code = table_a.code

RIGHT_JOIN.png

table_a.code table_a.* table_b.code table_b.*
201 201
202 202
203 203
NULL NULL 204
NULL NULL 205
NULL NULL 206

FULL JOIN

SELECT * 
  FROM table_a
  FULL JOIN table_b
         ON table_b.code = table_a.code

FULL_JOIN.png

table_a.code table_a.* table_b.code table_b.*
101 NULL NULL
102 NULL NULL
103 NULL NULL
201 201
202 202
203 203
NULL NULL 204
NULL NULL 205
NULL NULL 206

存在チェック

EXISTS

SELECT * 
  FROM table_a
 WHERE EXISTS(SELECT 1 FROM table_b WHERE table_b.code = table_a.code)

EXISTS.png

table_a.code table_a.*
201
202
203

NOT EXISTS

SELECT * 
  FROM table_a
 WHERE NOT EXISTS(SELECT 1 FROM table_b WHERE table_b.code = table_a.code)

NOT_EXISTS.png

table_a.code table_a.*
101
102
103
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?