跳轉到

資料庫基礎

開始之前

任務目標

在這個章節中,我們會完成:

  • 了解資料庫的基本概念
  • 了解資料庫正規化
  • 了解資料庫關聯類型

什麼是資料庫?

資料庫(Database)是用來儲存和管理資料的系統。你可以把它想像成一個電子化的檔案櫃,可以有效地儲存、查詢和管理大量資料。

關聯式資料庫

Django 預設使用關聯式資料庫(Relational Database),資料以表格(Table)的形式儲存:

id name email created_at
1 Alice [email protected] 2024-01-01
2 Bob [email protected] 2024-01-02
3 Charlie [email protected] 2024-01-03
  • Table(資料表):儲存同一類型資料的容器(如:users、articles)
  • Column(欄位):資料的屬性(如:name、email)
  • Row(列):一筆完整的資料記錄
  • Primary Key(主鍵):唯一識別每筆資料的欄位(通常是 id)

常見的關聯式資料庫

資料庫 說明
SQLite 輕量級,檔案型資料庫,Django 預設使用
PostgreSQL 功能強大,適合正式環境
MySQL 廣泛使用,效能良好
MariaDB MySQL 的開源分支

Django 預設使用 SQLite

Django 專案預設使用 SQLite,資料儲存在 db.sqlite3 檔案中。對於開發和小型專案來說非常方便,不需要額外安裝資料庫伺服器。但他畢竟還是一個檔案不一定適合用在正式環境。

資料庫正規化

正規化(Normalization)是設計資料庫時的重要原則,目的是減少資料重複、提高資料一致性。

為什麼需要正規化?

假設我們有一個訂單表,沒有正規化的設計:

order_id customer_name customer_email product_name product_price
1 Alice [email protected] iPhone 30000
2 Alice [email protected] MacBook 50000
3 Bob [email protected] iPhone 30000

問題:

  • Alice 的資料重複了兩次
  • iPhone 的價格重複了兩次
  • 如果要更新 Alice 的 email,需要更新多筆資料

正規化後的設計

將資料拆分成多個表:

customers 表

id name email
1 Alice [email protected]
2 Bob [email protected]

products 表

id name price
1 iPhone 30000
2 MacBook 50000

orders 表

id customer_id product_id
1 1 1
2 1 2
3 2 1

優點:

  • 每個資料只儲存一次
  • 更新資料只需要改一個地方
  • 資料一致性更好

正規化的等級

等級 說明
1NF 每個欄位只包含原子值(不可再分割)
2NF 符合 1NF + 非主鍵欄位完全依賴主鍵
3NF 符合 2NF + 非主鍵欄位不依賴其他非主鍵欄位

實務建議

在實務上,通常達到 3NF 就足夠了。過度正規化可能導致查詢需要太多 JOIN,影響效能。

資料庫關聯

資料表之間可以建立關聯(Relationship),這是關聯式資料庫的核心特性。

一對一(One-to-One)

一筆資料對應另一筆資料。

例如:一個使用者對應一個個人檔案

erDiagram
    User ||--|| Profile : has
    User {
        int id PK
        string username
        string email
    }
    Profile {
        int id PK
        int user_id FK
        string bio
        string avatar
    }

一對多(One-to-Many)

一筆資料對應多筆資料。

例如:一個作者可以有多篇文章

erDiagram
    Author ||--o{ Article : writes
    Author {
        int id PK
        string name
    }
    Article {
        int id PK
        int author_id FK
        string title
        text content
    }

多對多(Many-to-Many)

多筆資料對應多筆資料。

例如:一篇文章可以有多個標籤,一個標籤也可以對應多篇文章

erDiagram
    Article ||--o{ ArticleTag : has
    Tag ||--o{ ArticleTag : has
    Article {
        int id PK
        string title
    }
    Tag {
        int id PK
        string name
    }
    ArticleTag {
        int id PK
        int article_id FK
        int tag_id FK
    }

多對多關聯需要一個中間表(Junction Table)來連接兩個表。

任務結束

完成!

恭喜你完成了這個章節!現在你已經:

  • 了解資料庫的基本概念
  • 了解資料庫正規化
  • 了解資料庫關聯類型