Trung BìnhDatabase iconDatabase

Các loại relationships trong database design là gì?

One-to-One: mỗi record A liên kết đúng một record B — implement bằng UNIQUE FK: user_profiles.user_id REFERENCES users(id) UNIQUE.

  • Dùng để: tách optional/sensitive data (user + user_payment_info), tách heavy columns ít dùng, polymorphic extension tables.
  • One-to-Many: một A có nhiều B — FK trên bảng Many: posts.user_id REFERENCES users(id).
  • Phổ biến nhất trong relational design.
  • Many-to-Many: cần junction table với composite PK hoặc surrogate PK: enrollments(student_id, course_id, enrolled_at, grade) — junction table nên có thêm attributes liên quan đến relationship.
  • Self-referential: employees.manager_id REFERENCES employees(id) — org hierarchy, category tree, comment threads.
  • Polymorphic associations (anti-pattern trong SQL): comments(id, content, commentable_type, commentable_id) — commentable_id có thể tham chiếu posts hoặc videos — không có FK constraint, hard to maintain; prefer multiple FK columns với CHECK constraint, hoặc separate junction tables per type.
  • Pattern chọn: xác định cardinality trước, sau đó FK đặt ở phía Many, junction table cho M:N.

Xem toàn bộ Database cùng filter theo level & chủ đề con.

Mở danh sách Database