2011-05-05 203 views
2

(我用的工作臺),我有表questionsid, user_id, text和表users與領域id, namemysql alter table FOREIGN KEY!

我需要涉及這2個表!

我寫如下:

ALTER TABLE `mydb_development`.`questions` 
ADD CONSTRAINT fk_QueUsers_1 
FOREIGN KEY (`user_id`) 
REFERENCES `mydb_development`.`users`(`id`); 

,但我得到:

ERROR 1046: No database selected 
SQL Statement: 
ALTER TABLE `questions` 
ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) 

ERROR: Error when running failback script. Details follow. 

ERROR 1046: No database selected 
SQL Statement: 
CREATE TABLE `questions` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT, 
    `user_id` int(11) unsigned NOT NULL, 
    `text` text NOT NULL, 
    `security_token` varchar(40) NOT NULL, 
    `created_at` datetime NOT NULL, 
    `updated_at` datetime NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB AUTO_INCREMENT=373 DEFAULT CHARSET=utf8 

ERROR 1046: No database selected 
SQL Statement: 
ALTER TABLE `questions` 
ADD FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) 

ERROR: Error when running failback script. Details follow. 

..................... 

編輯: 我試圖做的:

USE `mydb_development`; 

ALTER TABLE `mydb_development`.`questions` 

ADD CONSTRAINT `fk_QueUsers_1` 

FOREIGN KEY (`user_id`) 

REFERENCES `mydb_development`.`users`(`id`); 

,我得到錯誤:

Error Code: 1005 
Can't create table 'survey_development.#sql-4ad_45' (errno: 150) 

不明白:S

編輯:

我的用戶表:

DROP TABLE IF EXISTS `mydb_development`.`users`; 
CREATE TABLE `mydb_development`.`users` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT, 
    `name` varchar(255) NOT NULL, 
    `email` varchar(255) NOT NULL, 
    PRIMARY KEY (`id`), 
    UNIQUE KEY `email` (`email`) 
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1; 
+0

post_create for'survey_development' – shevski 2011-05-05 07:29:28

+0

嘗試再次創建表格並添加約束條件添加索引 – shevski 2011-05-05 07:30:20

+0

請向我們展示編輯我的帖子的'users' – 2011-05-05 07:31:59

回答

0

輸入:

use `mydb_development`; 

變化約束名 'user_id說明' 的東西否則就像'fk_u ser_id」

+0

感謝您的回覆,我編輯了,但沒有,我更新了我的文章! – 2011-05-05 07:27:58

0

嘗試選擇你的數據庫,看它是否有什麼差別

USE `mydb_development`; 
+0

感謝您的迴應,我編輯了,但沒有,我更新了我的文章! – 2011-05-05 07:26:43

0

首先你要擺脫ERROR 1046: No database selected錯誤。

要做到這一點確保您:

  • 選擇與USE mydb_development;
  • 數據庫修改ALTER/CREATE語句包括分貝。例如。 ALTER TABLE mydb_development.questions
+0

感謝您的回覆,我編輯過,但沒有,我更新了我的帖子! – 2011-05-05 07:29:27

+0

看起來像一個不同的外鍵錯誤。尋找其他人對同一問題的解決方案:http://stackoverflow.com/search?q=foreign+key+150 – 2011-05-05 07:33:57