> For the complete documentation index, see [llms.txt](https://learnsql.gitbook.io/lernmysql/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://learnsql.gitbook.io/lernmysql/chuan-hoa-normalization/chua-bai-thuc-hanh-1.md).

# Chữa bài Thực Hành 1

Tôi thiết kế Quản lý blog: users: id, name posts: id,title,description comments: id,title,post\_id, user\_id Liệu có ok không? Hay kiểu thiết kế sau ổn hơn users: id, name posts: id,title,description comments: id,title,post\_id, user\_posts: id, user\_id,post\_id

Mình nói thẳng nhé: **cả 2 thiết kế của bạn đều chưa chuẩn**, nhưng cái thứ 2 còn **sai hướng hơn**.

Giờ mình phân tích kiểu “mentor review database thật” để bạn hiểu bản chất 👇

***

## ❌ THIẾT KẾ 1 (của bạn)

```
users: id, name
posts: id, title, description
comments: id, title, post_id, user_id
```

### ⚠️ Vấn đề:

#### 1. ❌ `posts` không biết ai viết

* Thiếu `user_id`\
  👉 Không xác định được tác giả bài viết

***

#### 2. ❌ `comments.title` là sai concept

* Comment không có “title”\
  👉 Nên là:

```
content / body
```

***

### ✅ Sửa lại đúng chuẩn:

```
users
- id
- name

posts
- id
- title
- description
- user_id (FK)

comments
- id
- content
- post_id (FK)
- user_id (FK)
```

👉 Đây là thiết kế **chuẩn thực tế 90% hệ thống**

***

## ❌ THIẾT KẾ 2 (của bạn)

```
users
posts
comments
user_posts
```

### ⚠️ Sai ở đâu?

#### ❌ Không cần `user_posts`

Vì:

👉 Quan hệ:

* 1 user → nhiều post
* 1 post → thuộc 1 user

\=> Đây là **1-N (one-to-many)**\
👉 Không phải many-to-many

***

### 📌 Khi nào mới cần bảng trung gian?

Chỉ khi:

👉 many-to-many

Ví dụ:

* user ↔ course
* post ↔ tag

***

## 🧠 TƯ DUY CHUẨN (RẤT QUAN TRỌNG)

### Xác định quan hệ:

| Quan hệ | Cách làm        |
| ------- | --------------- |
| 1 - 1   | FK              |
| 1 - N   | FK ở bảng N     |
| N - N   | bảng trung gian |

***

### Áp dụng vào bài blog:

* user → post = 1-N → `posts.user_id`
* post → comment = 1-N → `comments.post_id`
* user → comment = 1-N → `comments.user_id`

***

## 💎 THIẾT KẾ FINAL (CHUẨN SENIOR)

```
users
- id (PK)
- name

posts
- id (PK)
- title
- description
- user_id (FK)

comments
- id (PK)
- content
- post_id (FK)
- user_id (FK)
```

***

## 🔥 BONUS (LEVEL UP)

Nếu làm production thật:

### thêm:

```
posts
- created_at
- updated_at

comments
- created_at
```

***

### thêm index:

```
INDEX(user_id)
INDEX(post_id)
```

***

## 💥 KẾT LUẬN

| Thiết kế       | Đánh giá                     |
| -------------- | ---------------------------- |
| Thiết kế 1     | ❌ Thiếu user\_id trong posts |
| Thiết kế 2     | ❌ Sai bản chất quan hệ       |
| Thiết kế chuẩn | ✅ Như phần FINAL             |
