Database Schema Design และ Relationship

Database Schema Design คือการออกแบบโครงสร้างข้อมูลก่อนสร้างฐานข้อมูลจริง โดยใช้ ERD, Primary Key, Foreign Key, Relationship และหลัก Normalization เพื่อให้ข้อมูลถูกต้อง ลดความซ้ำซ้อน และค้นหาได้มีประสิทธิภาพ

Timeline/ประวัติศาสตร์

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart LR
  subgraph Era1["ยุคข้อมูลซ้ำ / Duplicated Data"]
    A["เก็บซ้ำหลายที่
แก้ไขยาก"] end subgraph Era2["ยุค ERD / Relationship Design"] B["Entity Relationship Diagram
ออกแบบก่อนสร้าง"] C["Primary/Foreign Key
เชื่อมความสัมพันธ์"] end subgraph Era3["ยุค Optimization / Scalable Schema"] D["Normalization
ลดความซ้ำ"] E["Index
ค้นหาเร็วขึ้น"] end A --> B --> C --> D --> E

แนวคิดสำคัญ

ตาราง Relationship

Relationship ตัวอย่าง วิธีออกแบบ
One-to-One User — Profile ใส่ FK ฝั่งใดฝั่งหนึ่งและกำหนด unique
One-to-Many User — Posts ใส่ user_id ใน posts
Many-to-Many Students — Courses สร้าง junction table

Mermaid Diagram: ERD ระบบบทเรียน

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
erDiagram
  USERS ||--o{ POSTS : "เขียน / writes"
  USERS ||--|| PROFILES : "มี / has"
  STUDENTS ||--o{ ENROLLMENTS : "ลงทะเบียน / enrolls"
  COURSES ||--o{ ENROLLMENTS : "มีผู้เรียน / has"
  USERS {
    int id PK
    string name
    string email
  }
  POSTS {
    int id PK
    int user_id FK
    string title
  }
  PROFILES {
    int id PK
    int user_id FK
    string bio
  }
  STUDENTS {
    int id PK
    string name
  }
  COURSES {
    int id PK
    string title
  }
  ENROLLMENTS {
    int student_id FK
    int course_id FK
  }

สมการคณิตศาสตร์: Many-to-Many ผ่าน Junction Table

JS×C

Code Example

-- Schema สำหรับ Many-to-Many ระหว่าง students และ courses
CREATE TABLE students (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100) NOT NULL
);

CREATE TABLE courses (
  id SERIAL PRIMARY KEY,
  title VARCHAR(150) NOT NULL
);

CREATE TABLE enrollments (
  student_id INT REFERENCES students(id),
  course_id INT REFERENCES courses(id),
  enrolled_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (student_id, course_id)
);

-- Index สำหรับค้นหาการลงทะเบียนตาม course
CREATE INDEX idx_enrollments_course_id
ON enrollments(course_id);

-- ตัวอย่างการใช้งาน:
-- ใช้ enrollments เป็น junction table เพื่อเชื่อม students กับ courses

กิจกรรมท้ายบท

  1. วาด ERD ระบบเรียนออนไลน์
  2. ระบุ Primary Key และ Foreign Key
  3. อธิบาย relationship แต่ละคู่
  4. เสนอ index ที่จำเป็นต่อการค้นหา

กลับสัปดาห์ที่ 11