2015-10-18 129 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;