2015-10-18 96 views
2

我试图在MySQL中使用MySQL工作台创建外键。但出现错误在MySQL中创建外键

$ Executing: 
ALTER TABLE `project_course`.`attendance` 
ADD CONSTRAINT `FK_Student` 
    FOREIGN KEY ('idStudent') 
    REFERENCES `project_course`.`student` ('userid') 
    ON DELETE NO ACTION 
    ON UPDATE NO ACTION; 

Operation failed: There was an error while applying the SQL script to the database. 
ERROR 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''idStudent') 
    REFERENCES `project_course`.`student` ('userid') 
    ON DELETE NO A' at line 3 
SQL Statement: 
ALTER TABLE `project_course`.`attendance` 
ADD CONSTRAINT `FK_Student` 
    FOREIGN KEY ('idStudent') 
    REFERENCES `project_course`.`student` ('userid') 
    ON DELETE NO ACTION 
    ON UPDATE NO ACTION 

回答

2

问题在于引号(在PC上它位于Enter键附近)。你已经使用它们而不是反引号(在PC上它位于Esc键下)。

ALTER TABLE `project_course`.`attendance` 
ADD CONSTRAINT `FK_Student` 
    FOREIGN KEY (`idStudent`) # Change them here around `idStudent` 
    REFERENCES `project_course`.`student` (`userid`) # and here around `userid` 
    ON DELETE NO ACTION 
    ON UPDATE NO ACTION; 
+0

如何更改?我用这个引号。我必须使用哪些引号? –

+0

谢谢/我用括号中没有引号的列名和它的执行。 –

+1

@ M.Namiz'这个引用是文字的,当你想给一个值作为字符串,就像插入语句中的定义一样,你应该使用反斜杠,在windows上的Esc键下 – Musa

0

穆萨的回答是正确的,但解释留下了一些欲望。这是一个更好的。

您对外键和引用子句中的列名使用了单引号字符。单引号表示MySQL中的字符串,但是在这些位置上需要列参考,即标识符。在你的情况下,根本不需要引号,因为在不使用引号时允许标识符中的所有字符(see the identifier rules for MySQL)。但是,如果您从用户输入或其他生成的数据创建查询(以避免sql注入并确保它可以工作,而不考虑使用的引用名称),总是会引用它。

通常引用意味着将标识符置于反引号内,始终有效。或者,您可以使用“双引号”,但前提是当前的SQL模式包含ANSI_QUOTES模式。否则双引号也表示字符串(如单引号)。如果您无法确保设置了ANSI_QUOTES模式,那么使用双引号是有点冒险的。

0

将此代码复制并粘贴到您的Mysql脚本编辑器中并运行。你将有两个表类别产品这些表具有cat_id作为外键

CREATE DATABASE IF NOT EXISTS dbdemo; 

USE dbdemo; 

CREATE TABLE categories(
    cat_id int not null auto_increment primary key, 
    cat_name varchar(255) not null, 
    cat_description text 
) ENGINE=InnoDB; 

CREATE TABLE products(
    prd_id int not null auto_increment primary key, 
    prd_name varchar(355) not null, 
    prd_price decimal, 
    cat_id int not null, 
    FOREIGN KEY fk_cat(cat_id) 
    REFERENCES categories(cat_id) 
    ON UPDATE CASCADE 
    ON DELETE RESTRICT 
)ENGINE=InnoDB;