I’m heaving a problem with adding a foreign key on table votes.
mysql> describe votes;
+----------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+------------------+------+-----+---------+----------------+
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| user_id | int(11) unsigned | NO | | NULL | |
| video_id | int(11) unsigned | NO | | NULL | |
| vote | int(11) | NO | | NULL | |
+----------+------------------+------+-----+---------+----------------+
mysql> describe user;
+----------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+------------------+------+-----+---------+----------------+
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| email | varchar(256) | NO | MUL | NULL | |
| password | varchar(32) | NO | | NULL | |
| name | varchar(24) | NO | | NULL | |
+----------+------------------+------+-----+---------+----------------+
Votes.user_id is a foreign key to User.id. Bot have the same time however when I run:
mysql> alter table `votes`
add CONSTRAINT `votes_FK_1`
FOREIGN KEY (`user_id`) REFERENCES `user` (`id`);
MySQL is throwing a good old 150
ERROR 1005 (HY000): Can't create table 'crocko.#sql-6e1_3c5' (errno: 150)
What am I doing wrong?
You need to check whether you have any data stored in your table.. If yes, then you need to remove them..
Or, If your MySQL DB Engine is MyISAM, you won’t be able to add foreign key after table is created..
You can check how to change it to InnoDB..