MySQL中的错误代码1022

时间:2015-07-10 00:14:11

标签: mysql database duplicates key

我对数据库处理很陌生。我试图创建表

ASSIGNMENT (ProjectID, EmployeeNumber, HoursWorked)

ProjectIDEmployeeNumber是表ASSIGNMENT的复合主键和表PROJECTEMPLOYEE的外键(见下文)

这是我的数据:

CREATE TABLE IF NOT EXISTS ASSIGNMENT( ProjectID Int(4) NOT NULL AUTO_INCREMENT, EmployeeNumber Int(4) NOT NULL, HoursWorked Int(4) NOT NULL, PRIMARY KEY (ProjectID), UNIQUE (EmployeeNumber), KEY ProjectFK (ProjectID), KEY EmployeeFK (EmployeeNumber), CONSTRAINT ProjectFK FOREIGN KEY (ProjectID) REFERENCES PROJECT(ProjectID) ON DELETE CASCADE, CONSTRAINT EmployeeFK FOREIGN KEY (EmployeeNumber) REFERENCES EMPLOYEE(EmployeeNumber) );

我已经看过很多像这样的例子,但是这个实例的独特之处在于MySQL不允许在一个表中使用两个主键所以我使EmployeeNumber成为一个独特的键。

以下是整个架构的数据:

CREATE SCHEMA IF NOT EXISTS WPC;

CREATE TABLE IF NOT EXISTS DEPARTMENT( Department Char(30) NOT NULL DEFAULT 'Human Resources', BudgetCode Int(20) NOT NULL, OfficeNumber Int(10) NOT NULL, Phone Char(12) NULL, PRIMARY KEY (Department));

CREATE TABLE IF NOT EXISTS EMPLOYEE( EmployeeNumber Int(4) NOT NULL AUTO_INCREMENT, FirstName Char(25) NOT NULL, LastName Char(25) NOT NULL, Department Char(30) NOT NULL, Phone Char(17) NULL, Email VarChar(100) NOT NULL, PRIMARY KEY (EmployeeNumber), UNIQUE KEY Email (Email), KEY DepartmentFK (Department), CONSTRAINT DepartmentFK FOREIGN KEY (Department) REFERENCES DEPARTMENT(Department) ON DELETE RESTRICT ON UPDATE CASCADE );

CREATE TABLE IF NOT EXISTS PROJECT( ProjectID Int(4) AUTO_INCREMENT, ProjectName Char(20) NOT NULL, Department Char(30) NOT NULL, MaxHours Int(14) NOT NULL DEFAULT 100, StartDate Char(10) NOT NULL, EndDate Char(10) NULL, PRIMARY KEY (ProjectID), KEY ProjectFK (Department), CONSTRAINT ProjectFK FOREIGN KEY (Department) REFERENCES DEPARTMENT(Department) ON DELETE RESTRICT ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=1000;

SET @@AUTO_INCREMENT_INCREMENT=100;

CREATE TABLE IF NOT EXISTS ASSIGNMENT( ProjectID Int(4) NOT NULL AUTO_INCREMENT, EmployeeNumber Int(4) NOT NULL, HoursWorked Int(4) NOT NULL, PRIMARY KEY (ProjectID), UNIQUE (EmployeeNumber), KEY ProjectFK (ProjectID), KEY EmployeeFK (EmployeeNumber), CONSTRAINT ProjectFK FOREIGN KEY (ProjectID) REFERENCES PROJECT(ProjectID) ON DELETE CASCADE, CONSTRAINT EmployeeFK FOREIGN KEY (EmployeeNumber) REFERENCES EMPLOYEE(EmployeeNumber) );

ProjectIDEmployeeNumber是表ASSIGNMENT中的复合主键。它们也是引用表PROJECTEMPLOYEE的外键。

ASSIGNMENT表外,数据库的所有内容都很好。当我运行ASSIGNMENT的脚本时,我得到了这个回复:

Error Code: 1022. Can't write; duplicate key in table 'assignment'.

1 个答案:

答案 0 :(得分:1)

用于外键约束的名称在数据库中必须是唯一的。您尝试在不同的表格上为FK使用相同的名称。

您在ProjectFK表上使用名称PROJECT,并尝试在ASSIGNMENT表上再次使用相同的名称。

更改其中一个表格上的FK约束名称。