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?

DBにおけるリレーションとは

Posted at

今日のトピック

  • DBにおけるリレーションとは

DBにおけるリレーションとは

端的に言うと、テーブル同士が持つ「関係性」のこと。
この関係性(リレーションシップ)をテーブル間で適切に定義し、データの整合性を保つためには、以下のキー概念が基本となる。

  • 主キー(Primary Key - PK):テーブル内の各レコードを一意に識別するためのキー
  • 外部キー(Foreign Key -FK): 他のテーブルの主キーを参照することで、テーブル間の関連付けを行うためのキー

リレーションシップには、主に以下の3つパターンがある。

  • 1対1
  • 1対多
  • 多対多

これら3つのリレーションシップをどのように構築していくかについて記載する。

1対1リレーションシップ

例)Users テーブルと UserProfiles テーブル(ユーザーは1つのプロフィールを持ち、プロフィールは1人のユーザーに属する)

  • DBスキーマ設計 (SQL例):
Users
id (PK), username, email, etc.
UserProfiles 
id (PK), user_id (FK, UNIQUE references Users.id), etc.

user_id に UNIQUE 制約をかけることで1対1を保証する。
もしくは、UserProfiles の主キーを user_id にする設計も考えられる。

1対多リレーションシップ

例)Authors テーブルと Posts テーブル(著者は多数の投稿を持つことができ、投稿は1人の著者に属する)

  • DBスキーマ設計 (SQL例):
Authors
id (PK), name, etc.
Posts
id (PK), title, content, author_id (FK references Authors.id)

多対多リレーションシップ

例) Posts テーブルと Tags テーブル(投稿は多数のタグを持つことができ、タグは多数の投稿に適用できる)

  • DBスキーマ設計 (SQL例):
Posts
id (PK), title, content, etc.
Tags
id (PK), name, etc.
Post_Tags(中間テーブル)
post_id (FK references Posts.id),tag_id (FK references Tags.id), PRIMARY KEY (post_id, tag_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?