To ensure each employee is unique, set employeeid as the primary key or unique constraint. To ensure each employee can only belong to an existing department, create a foreign key constraint on deptid.
正确答案是:B: Set employeeid as the primary key, and create a foreign key constraint on deptid。
专业分析:
1. **唯一性和主键约束:**
- 每个员工(employee)在员工表(employee table)中应该是唯一的,这意味着每个员工的 `employeeid` 应该是唯一的。因此,需要将 `employeeid` 设置为主键。
2. **外键约束:**
- 为了确保每个员工只能属于一个已经存在的部门,需要在 `employee` 表中的 `deptid` 上创建一个外键约束,引用 `department` 表中的 `departid`。这样可以确保 `employee` 表中的 `deptid` 值必须在 `department` 表中存在。
具体实现如下:
```sql
CREATE TABLE department (
departid int not null primary key,
deptname varchar(20) not null
);
CREATE TABLE employee (
employeeid int not null primary key,
deptid int not null,
ename varchar(20) not null,
job varchar(10),
sal decimal(10,2),
FOREIGN KEY (deptid) REFERENCES department(departid)
);
```
### 其他选项的分析:
- **A: Set employeeid and deptid as a composite primary key**
- 这种方法将 `employeeid` 和 `deptid` 设为复合主键,这意味着一个员工在一个特定部门是唯一的,但一个员工可以在多个部门中存在,这不符合实际需求。
- **C: Set employeeid as the primary key, and create a unique constraint on deptid**
- 这种方法会确保 `employeeid` 是唯一的,但 `deptid` 上的唯一约束会限制每个部门只能有一个员工,这显然是不合理的。
- **D: Create a unique constraint on deptid, and create a foreign key constraint on deptid**
- 这种方法会确保每个部门只能有一个员工,这同样是不合理的。同时,它没有解决 `employeeid` 的唯一性问题。
因此,选项 B 是最恰当的选择。