FOREIGN KEY约束帮助Mysql

时间:2018-07-04 17:40:55

标签: mysql sql mysql-error-1064

我正在查看mysql,正在创建表时编写外键。但是,当我创建外键时,会收到语法错误。

CREATE TABLE IF NOT EXISTS staff (
    staff_id INT(5) NOT NULL,
    staff_first_name VARCHAR(20) NOT NULL,
    staff_last_name VARCHAR(20) NOT NULL,
    staff_phone_number VARCHAR(15) NOT NULL,
    staff_email_address VARCHAR(30) NOT NULL,
    CONSTRAINT staff_id_pk PRIMARY KEY (staff_id)
    CONSTRAINT staff_id_fk FOREIGN KEY (staff_id)
    REFERENCES computer_staff (staff_id)
);

有人可以在这里看到我做错了什么吗?


编辑:

我收到的错误报告为:

  

19:35:55 CONSTRAINT staff_id_fk FOREIGN KEY(staff_id),REFERENCES computer_staff(staff_id))错误代码:1064。检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在“ CONSTRAINT staff_id_fk FOREIGN KEY(staff_id),REFERENCES computer_staff(staff_')第1行附近使用0.00025秒

更新:错误代码:1215。无法添加外键约束0.110秒

一个如何解决错误代码1215?

2 个答案:

答案 0 :(得分:3)

尝试此代码

CREATE TABLE IF NOT EXISTS staff (
staff_id INT(5) NOT NULL,
staff_first_name VARCHAR(20) NOT NULL,
staff_last_name VARCHAR(20) NOT NULL,
staff_phone_number VARCHAR(15) NOT NULL,
staff_email_address VARCHAR(30) NOT NULL,
Foregn_Key int,
CONSTRAINT staff_id_pk PRIMARY KEY (staff_id),
CONSTRAINT staff_id_fk FOREIGN KEY (Foregn_Key)
REFERENCES computer_staff (Foregn_Key)
);

答案 1 :(得分:2)

您缺少逗号:

CREATE TABLE IF NOT EXISTS staff (
    staff_id INT(5) NOT NULL,
    staff_first_name VARCHAR(20) NOT NULL,
    staff_last_name VARCHAR(20) NOT NULL,
    staff_phone_number VARCHAR(15) NOT NULL,
    staff_email_address VARCHAR(30) NOT NULL,
    CONSTRAINT staff_id_pk PRIMARY KEY (staff_id), -- here
    CONSTRAINT staff_id_fk FOREIGN KEY (staff_id)
    REFERENCES computer_staff (staff_id)
);