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でjoinをする際の色んな書き方のtips

Last updated at Posted at 2025-01-11

はじめに

上級者のSQLを見ると、joinをする際に色んな記法や省略記法が使われている事があると思います。
調べたことをまとめます

jojnをする際に、これから結合するテーブルのテーブル名は省略できる

SELECT
  *
FROM
  posts JOIN comments ON (comments.post_id = posts.id)
SELECT
  *
FROM
  posts JOIN comments ON (post_id = posts.id)

どちらでも出力結果は同じです。

+----+---------+----+---------+-------------+
| id | message | id | post_id | comment     |
+----+---------+----+---------+-------------+
|  1 | post-1  |  1 |       1 | comment-1-1 |
|  1 | post-1  |  2 |       1 | comment-1-2 |
|  3 | post-3  |  3 |       3 | comment-3-1 |
+----+---------+----+---------+-------------+

同じカラム名で結合する際はonを使わず、usingキーワードで結合できる

両者にidというカラムがあれば、idで結合します

SELECT
  *
FROM
  posts JOIN comments using (id)
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?