I am trying to create two tables in MySQL database called class_members
and history
. The class_members
table contains information about the members and is created as:
CREATE TABLE `class_members` (
`id` int(11) NOT NULL,
`username` varchar(65) NOT NULL DEFAULT '',
`password` varchar(65) NOT NULL DEFAULT '',
`email` varchar(65) NOT NULL,
`mod_timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `username_UNIQUE` (`username`),
UNIQUE KEY `id_UNIQUE` (`id`),
UNIQUE KEY `email_UNIQUE` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
The class_members
tables is successfully created.
I am facing the problem when creating history
table which contains foreign key
reference to class_members
.
The command which I used is as follows:
CREATE TABLE `History` (
`history_id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(65) NOT NULL DEFAULT '',
`timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`ip` VARCHAR(20) NOT NULL,
PRIMARY KEY (`history_id`),
CONSTRAINT `fk_history_member` FOREIGN KEY (`username`)
REFERENCES `class_members` (`username`)
ON UPDATE CASCADE);
When I execute the above command I get this error:
ERROR 1005 (HY000): Can't create table 'testDB.History' (errno: 150)
I tried to find why I cannot read the History
table
(about ERROR 1005)
but I cannot understand why
Following Up on Comments, I created a new database and tried creating using the above command and I still get the error. See Attached Pic
Updated (Solved)
I found why the error in the above screenshot occurs. To solve that we have to add ENGINE=InnoDB DEFAULT CHARSET=utf8
to the end of the History table creation command.
CREATE TABLE `History` (
`history_id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(65) NOT NULL DEFAULT '',
`timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`ip` VARCHAR(20) NOT NULL,
PRIMARY KEY (`history_id`),
CONSTRAINT `fk_history_member` FOREIGN KEY (`username`)
REFERENCES `class_members` (`username`)
ON UPDATE CASCADE)ENGINE=InnoDB DEFAULT CHARSET=utf8;
This works perfectly.