(I using workbench) i have table questions
with id, user_id, text
and table users
with fields id, name
I need to relate this 2 tables!
I write following:
ALTER TABLE `mydb_development`.`questions`
ADD CONSTRAINT fk_QueUsers_1
FOREIGN KEY (`user_id`)
REFERENCES `mydb_development`.`users`(`id`);
but i get:
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.
.....................
EDIT: I tried to do:
USE `mydb_development`;
ALTER TABLE `mydb_development`.`questions`
ADD CONSTRAINT `fk_QueUse开发者_JS百科rs_1`
FOREIGN KEY (`user_id`)
REFERENCES `mydb_development`.`users`(`id`);
and i get error:
Error Code: 1005
Can't create table 'survey_development.#sql-4ad_45' (errno: 150)
DOnt understand:S
EDIT:
my user table:
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;
This seems to be mysql bug:
Read http://forums.mysql.com/read.php?22,19755,19755
Try to index the 'user_id' and run the script again.
Try selecting your database to see if it makes any difference
USE `mydb_development`;
First of all you want to get rid of the ERROR 1046: No database selected
errors.
To do this make sure that you either:
- Select a database with
USE mydb_development;
- Modify the
ALTER/CREATE
statements to include the db. E.g.ALTER TABLE mydb_development.questions
enter:
use `mydb_development`;
change the constraint name 'user_id' to something else like 'fk_user_id'
精彩评论