2015-06-10 72 views
1

我試圖從SQL轉儲創建數據庫。 我寫的是這樣的:從SQL轉儲添加外鍵失敗

CREATE DATABASE IF NOT EXISTS rsa_database; 

CREATE TABLE IF NOT EXISTS `keys` (
    `id` int(11) NOT NULL auto_increment, 
    `public_key` varchar(20) collate latin1_general_ci NOT NULL, 
    `private_key` varchar(30) collate latin1_general_ci NOT NULL, 
    PRIMARY KEY (`id`) 
); 

CREATE TABLE IF NOT EXISTS `user` (
    `id` int(11) NOT NULL auto_increment, 
    `firstname` varchar(20) collate latin1_general_ci NOT NULL, 
    `lastname` varchar(20) collate latin1_general_ci NOT NULL, 
    `date_of_birth` varchar(20) collate latin1_general_ci NOT NULL, 
    `zip` varchar(20) collate latin1_general_ci NOT NULL, 
    `city` varchar(20) collate latin1_general_ci NOT NULL, 
    `street` varchar(20) collate latin1_general_ci NOT NULL, 
    `number` varchar(20) collate latin1_general_ci NOT NULL, 
    `tel` varchar(20) collate latin1_general_ci NOT NULL, 
    `email` varchar(20) collate latin1_general_ci NOT NULL, 
    `k_id` int(11) NOT NULL, 
    PRIMARY KEY (`id`), 
    FOREIGN KEY (k_id) REFERENCES keys(id) 
); 

但我的MySQL服務器拋出此錯誤消息:

ERROR 1064 (42000) at line 78: 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 'keys(id)' at line 1 

我嘗試了不同的符號,看了一些文檔,但我找不出我的失敗。
謝謝!

回答

2

由於keys是MySQL中的reserved word,需要用反引號每次引用名爲keys表時引用它:

CREATE TABLE IF NOT EXISTS `user` (
    `id` int(11) NOT NULL auto_increment, 
    `firstname` varchar(20) collate latin1_general_ci NOT NULL, 
    `lastname` varchar(20) collate latin1_general_ci NOT NULL, 
    `date_of_birth` varchar(20) collate latin1_general_ci NOT NULL, 
    `zip` varchar(20) collate latin1_general_ci NOT NULL, 
    `city` varchar(20) collate latin1_general_ci NOT NULL, 
    `street` varchar(20) collate latin1_general_ci NOT NULL, 
    `number` varchar(20) collate latin1_general_ci NOT NULL, 
    `tel` varchar(20) collate latin1_general_ci NOT NULL, 
    `email` varchar(20) collate latin1_general_ci NOT NULL, 
    `k_id` int(11) NOT NULL, 
    PRIMARY KEY (`id`), 
    FOREIGN KEY (`k_id`) REFERENCES `keys`(`id`) 
); 
+0

謝謝,我發現了,如何解決它,而不是我爲什麼必須;) – DevWurm

+0

默認情況下,mysqldump引用所有表格和列名與反標記,所以我推測有人在生成後手動編輯文件。 –

+0

我的建議是避免使用表名和列名的保留字。如果你這樣做,那麼你不必擔心這種類型的問題。 –

相關問題