2016-07-22 137 views
-1

當試圖創建一個表,並與下面的查詢修改它:Mysql的外鍵

CREATE TABLE `sms_codes` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `user_id` int(11) NOT NULL, 
    `code` varchar(6) NOT NULL, 
    `status` int(1) NOT NULL DEFAULT '0', 
    `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 
    PRIMARY KEY (`id`), 
    KEY `user_id` (`user_id`) 
) 

ALTER TABLE `sms_codes` 
    ADD CONSTRAINT `sms_codes_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; 

我得到了錯誤:

#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 'ALTER TABLE `sms_codes` ADD CONSTRAINT `sms_codes_ibfk_1` FOREIGN KEY (`user_' at line 11

+3

添加分號的'CREATE結束後TABLE'語句。 –

回答

0

每個語句需要用分隔;分離。所以添加;CREATE TABLE結束以同樣的方式,你怎麼在ALTER TABLE聲明的末尾添加;

在這一行:

KEY `user_id` (`user_id`) 
); <-- here