2
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?

More than 1 year has passed since last update.

外部キーの考え方

Last updated at Posted at 2023-07-02

DBテーブルというものを作ってみてPlantUMLでER図を書いてみて腹に落ちたときの事。

ある本(※1)での解説では社員の部署のデータを紐付けるためにある。
メインが社員で、従属するテーブルが部署のデータ。
とあったがこの発想を逆転した時に納得できた。

たとえば、作品を登録してあるリストがのマスターテーブルであり、
そこから自分の好きな作品を取り出すと考えると腹に落ちた。

外部キーとはキーとして作品のリストがある場所の扉を開けるための鍵であると発想すると外部キーの役割が素直に納得できた。

例えば、
本や、アニメ作品のマスターデータが入っているテーブルからデータを引っ張ってくる。
その時に利用するのが外部キー

自分が好きな作品を選んでノートに追加して書いていく感じで増やしていく。
その時に使用するのが外部キー

アニメのマスターテーブル

| id | title | genre | director | studio |
|----|-------|-------|----------|--------|
| 1 | Attack on Titan | Action, Dark Fantasy | Tetsurō Araki | Wit Studio |
| 2 | Legend of the Galactic Heroes | Space Opera, Military Science Fiction | Noboru
| 3 | Ashita no Joe | Sports, Drama | Osamu Dezaki | Mushi Production |
Ishiguro | Artland, Magic Bus |
| 4 | Nausicaä of the Valley of the Wind | Adventure, Fantasy, Post-Apocalyptic | Hayao Miyazaki | Topcraft |
| 5 | One Piece | Action, Adventure, Comedy | Kōnosuke Uda | Toei Animation |

ユーザーの好きなアニメ

| id | user_id | anime_id |
|----|---------|----------|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 3 |
| 4 | 2 | 4 |
| 5 | 2 | 5 |

参考

※1 達人に学ぶDB設計 徹底指南書

2
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
2
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?