创建员工表
设计一个表来存储员工联系方式,通过适当的数据类型和约束来确保数据完整性。
employees
表已经为你创建好了。如果你没有看到它,你可以使用以下命令创建它:
CREATE TABLE employees (
employee_id SERIAL PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL
);
任务
- 在 PostgreSQL 中创建一个名为
employee_contacts
的表。该表应包含以下列:contact_id
(主键)、employee_id
(外键,引用 employees
表)、phone_number
(唯一)和 email
(非空)。
- 确保
employee_id
列正确引用 employees
表中的 employee_id
列。
要求
contact_id
列必须是自增主键。
phone_number
列必须是唯一的。
email
列不允许 NULL
值。
employee_id
列必须是引用 employees
表的外键。
- 使用
psql
执行 SQL 命令。
示例
employees
和 employee_contacts
表应具有以下结构:
Table "public.employees"
Column | Type | Collation | Nullable | Default
-------------+-----------------------+-----------+----------+------------------------------------------------
employee_id | integer | | not null | nextval('employees_employee_id_seq'::regclass)
first_name | character varying(50) | | |
last_name | character varying(50) | | |
Indexes:
"employees_pkey" PRIMARY KEY, btree (employee_id)
Referenced by:
TABLE "employee_contacts" CONSTRAINT "employee_contacts_employee_id_fkey" FOREIGN KEY (employee_id) REFERENCES employees(employee_id)
Table "public.employee_contacts"
Column | Type | Collation | Nullable | Default
----------------+------------------------+-----------+----------+--------------------------------------------------
contact_id | integer | | not null | nextval('employee_contacts_contact_id_seq'::regclass)
employee_id | integer | | |
phone_number | character varying(20) | | |
email | character varying(100) | | not null |
Indexes:
"employee_contacts_pkey" PRIMARY KEY, btree (contact_id)
"employee_contacts_phone_number_key" UNIQUE CONSTRAINT, btree (phone_number)
Foreign-key constraints:
"employee_contacts_employee_id_fkey" FOREIGN KEY (employee_id) REFERENCES employees(employee_id)
提示
- 使用
CREATE TABLE
语句创建表。
- 使用
SERIAL
数据类型为 contact_id
列自动生成唯一的整数值。
- 使用
PRIMARY KEY
约束来定义主键。
- 使用
UNIQUE
约束来确保 phone_number
列包含唯一值。
- 使用
NOT NULL
约束来确保 email
列不包含 NULL
值。
- 使用
FOREIGN KEY
约束在 employee_contacts
表中的 employee_id
列和 employees
表中的 employee_id
列之间创建外键关系。
- 记住在使用 SQL 命令之前,使用
sudo -u postgres psql
连接到 PostgreSQL 数据库。