改善物件與資料的對應
Small Business Development Center 的 client 資料表先前在定義時,沒有包含客戶的聯絡人。資料庫團隊的直覺做法,是直接在 client 表新增 contact_name 和 contact_email 欄位。不過,基於你對正確資料組織的判斷,你反對這個做法。未來同一個聯絡人可能會在多個資料表中被參照。這個練習中,你將為客戶與聯絡人資訊設計更佳的資料表結構,清楚分開 client 與 contact 兩個物件。
回顧先前 client 資料表的定義:
CREATE TABLE client (
id SERIAL PRIMARY KEY,
name VARCHAR(50),
site_url VARCHAR(50),
num_employees SMALLINT,
num_customers INTEGER
);
本練習屬於課程
建立 PostgreSQL 資料庫
練習說明
- 建立
contact資料表,包含欄位id(主鍵)、name(最大長度 50)、email(最大長度 50)。 - 變更
client資料表,新增contact_id欄位作為外鍵。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
-- Create the contact table
___ ___ ___ (
-- Define the id primary key column
___ SERIAL ___ ___,
-- Define the name column
___ ___(50) NOT NULL,
-- Define the email column
___ VARCHAR(___) NOT NULL
);
-- Add contact_id to the client table
ALTER TABLE ___ ADD ___ INTEGER NOT NULL;
-- Add a FOREIGN KEY constraint to the client table
ALTER TABLE ___ ADD CONSTRAINT fk_c_id FOREIGN KEY (___) REFERENCES ___(id);