Usually I worked with PostgreSQL and never had a problem, but now I need to work with MySQL and I experiencing some troubles.
I am creating a table in database user_main_db. There is some problem with Foreign keys, phpMyAdmin always gives me next error:
1005 – Can’t create table ‘user_main_db.user_main’ (errno: 150) (
engine=InnoDB&page=Status&token=136fdbb820093986c79180b24adb304d”>Details…)
This is the table I am trying to create in database user_main_db:
CREATE TABLE user_main
(
uid INTEGER,
fn VARCHAR(40) NOT NULL,
ava VARCHAR(255),
gender tinyint(1) NOT NULL,
dob DATE NOT NULL,
country_id INTEGER,
PRIMARY KEY (uid),
FOREIGN KEY ( uid ) REFERENCES user_basic_db.user_basic(uid) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY ( country_id ) REFERENCES countries_db.countries(country_id) ON DELETE CASCADE ON UPDATE CASCADE
);
This is table user_basic in database user_basic_db:
CREATE TABLE user_basic
(
uid INTEGER AUTO_INCREMENT,
email VARCHAR(40) NOT NULL,
password VARCHAR(40) NOT NULL,
PRIMARY KEY (uid)
);
This is table countries in database countries_db:
CREATE TABLE countries(
country_id INTEGER PRIMARY KEY AUTO_INCREMENT,
country VARCHAR(40) NOT NULL UNIQUE
)
The strange thing is when I define the table as follows:
CREATE TABLE user_main
(
uid INTEGER PRIMARY KEY REFERENCES user_basic_db.user_basic(uid) ON DELETE CASCADE ON UPDATE CASCADE,
VARCHAR(40) NOT NULL,
ava VARCHAR(255),
gender tinyint(1) NOT NULL,
dob DATE NOT NULL,
country_id INTEGER REFERENCES countries_db.countries(country_id) ON DELETE CASCADE ON UPDATE CASCADE
);
the query runs successfully but FOREIGN KEYS are not created, when I open ‘relational view’ there are no references to uid and country_id and I can make insert to user_main(country_id) even if there is no country with such id.
Please help someone. Thank you.
Check out the MySQL manual about foreign key constrains:
Sounds familiar, doesn’t it!?
Better drop the tables and create it new with a well formed syntax, something like this:
This should do the job.