I'm trying to create a table with this sql:
CREATE TABLE angestellte (
PersonalNr int(11) NOT NULL AUTO_INCREMENT,
Vorname varchar(50) NOT NULL,
Nachname varchar(50) NOT NULL,
Beruf varchar(50) NOT NULL,
Gehalt int(11) NOT NULL,
arbeitetInAbteilung int(11) NOT NULL,
PRIMARY KEY (PersonalNr),
FOREIGN KEY abteilung (AbteilungID)
)
ENGINE=InnoDB;
But I get only the message
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')
ENGINE=InnoDB' at line 10
I looked really can't find my mistake but think it's probably something obvious I just don't see.
Supposing you have a table where a field (arbeitetInAbteilung) references a row in another table (say arbeiten), you need to define it like this:
CREATE TABLE `angestellte` (
`PersonalNR` INT(11) NOT NULL AUTO_INCREMENT,
...other fields...
`arbeitetInAbteilung` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`PersonalNR`),
INDEX `FK__arbeiten` (`arbeitetInAbteilung`),
CONSTRAINT `FK__arbeiten` FOREIGN KEY (`arbeitetInAbteilung`)
REFERENCES `arbeiten` (`arbeitID`)
ON UPDATE CASCADE
ON DELETE CASCADE
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
This means that an index will be created to index the field you specify (arbeitetInAbteilung). Then a constraint will be set in place so that this index is linked to the values of another field in a different table, which could be defined like this:
CREATE TABLE `arbeiten` (
`arbeitID` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`arbeitID`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
Note that the two fields must be absolutely identical; if they are text fields, they need to have the same collation; they must be both either NULL or NOT NULL; et cetera. The slightest difference will yield a "Foreign key constraint is incorrectly formed" error, and you'll need to show the engine status for InnoDB and parse its output to understand why.
The ON UPDATE and ON DELETE define what happens when you change a value in the master (arbeiten) table, or you delete it. If the ID 123 becomes 456, CASCADE means that all the rows that referred 123 will now refer 456. Another possibility would be to prevent the operation (RESTRICT), or set the mismatched rows to NULL (SET NULL).
As already commented, your FK syntax is total wrong.
FOREIGN KEY abteilung (AbteilungID)
should be
FOREIGN KEY some_column REFERENCES abteilung (AbteilungID)
Here, some_column should be replaced by the column which you want to designate as the referencing key and the definition of this column should exactly match with column AbteilungID of table abteilung
Related
When I execute the follow two queries (I have stripped them down to absolutely necessary):
mysql> CREATE TABLE foo(id INT PRIMARY KEY);
Query OK, 0 rows affected (0.01 sec)
mysql> CREATE TABLE bar ( id INT, ref INT, FOREIGN KEY (ref) REFERENCES foo(id)) ENGINE InnoDB;
I get the following error:
ERROR 1005 (HY000): Can't create table './test/bar.frm' (errno: 150)
Where the **** is my error? I haven't found him while staring at this for half an hour.
From FOREIGN KEY Constraints
If you re-create a table that was
dropped, it must have a definition
that conforms to the foreign key
constraints referencing it. It must
have the right column names and types,
and it must have indexes on the
referenced keys, as stated earlier. If
these are not satisfied, MySQL returns
error number 1005 and refers to error
150 in the error message.
My suspicion is that it's because you didn't create foo as InnoDB, as everything else looks OK.
Edit: from the same page -
Both tables must be InnoDB tables and they must not be TEMPORARY tables.
You can use the command SHOW ENGINE INNODB STATUS to get more specific information about the error.
It will give you a result with a Status column containing a lot of text.
Look for the section called LATEST FOREIGN KEY ERROR which could for example look like this:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
190215 11:51:26 Error in foreign key constraint of table `mydb1`.`contacts`:
Create table `mydb1`.`contacts` with foreign key constraint failed. You have defined a SET NULL condition but column 'domain_id' is defined as NOT NULL in ' FOREIGN KEY (domain_id) REFERENCES domains (id) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT contacts_teams_id_fk FOREIGN KEY (team_id) REFERENCES teams (id) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT' near ' ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT contacts_teams_id_fk FOREIGN KEY (team_id) REFERENCES teams (id) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT'.
To create a foreign key ,
both the main column and the reference column must have same definition.
both tables engine must be InnoDB.
You can alter the engine of table using this command , please take the backup before executing this command.
alter table [table name] ENGINE=InnoDB;
I had the same problem, for those who are having this also:
check the table name of the referenced table
I had forgotten the 's' at the end of my table name
eg table Client --> Clients
:)
Apart form many other reasons to end up with MySql Error 150 (while using InnoDB), One of the probable reason, is the undefined KEY in the create statement of the table containing the column name referenced as a foreign key in the relative table.
Let's say the create statement of master table is -
CREATE TABLE 'master_table' (
'id' int(10) NOT NULL AUTO_INCREMENT,
'record_id' char(10) NOT NULL,
'name' varchar(50) NOT NULL DEFAULT '',
'address' varchar(200) NOT NULL DEFAULT '',
PRIMARY KEY ('id')
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and the create syntax for the relative_table table where the foreign key constraint is set from primary table -
CREATE TABLE 'relative_table' (
'id' int(10) NOT NULL AUTO_INCREMENT,
'salary' int(10) NOT NULL DEFAULT '',
'grade' char(2) NOT NULL DEFAULT '',
'record_id' char(10) DEFAULT NULL,
PRIMARY KEY ('id'),
CONSTRAINT 'fk_slave_master' FOREIGN KEY ('record_id') REFERENCES 'master' ('record_id')
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
This script is definitely going to end with MySql Error 150 if using InnoDB.
To solve this, we need to add a KEY for the The column record_id in the master_table table and then reference in the relative_table table to be used as a foreign_key.
Finally, the create statement for the master_table, will be -
CREATE TABLE 'master_table' (
'id' int(10) NOT NULL AUTO_INCREMENT,
'record_id' char(10) NOT NULL,
'name' varchar(50) NOT NULL DEFAULT '',
'address' varchar(200) NOT NULL DEFAULT '',
PRIMARY KEY ('id'),
KEY 'record_id' ('record_id')
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I had very same problem and the reason was the "collation" of columns was different. One was latin1 while the other was utf8
This may also happen if you have not given correct column name after "references" keyword.
i have customer table with nid_c,nama_customer, and more field ..
second table I have kendaraan with nopol,nid_c,nama_customer, and more field ..
I try make relation between this table..
I want update data nid_c and nama_customer on kendaraan table when I update customer table.
I got error message here.
Executing SQL script in server
ERROR: Error 1215: Cannot add foreign key constraint
SQL Code:
-- -----------------------------------------------------
-- Table `BengkelBiru`.`kendaraan`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `BengkelBiru`.`kendaraan` (
`NOPOL` VARCHAR(12) NOT NULL,
`NID_C` VARCHAR(7) NULL DEFAULT NULL,
`NAMA_CUSTOMER` VARCHAR(25) NULL DEFAULT NULL,
`MERK` VARCHAR(15) NULL DEFAULT NULL,
`TYPE` VARCHAR(25) NULL DEFAULT NULL,
`CC` VARCHAR(4) NULL DEFAULT NULL,
`TAHUN` VARCHAR(4) NULL DEFAULT NULL,
`WARNA` VARCHAR(10) NULL DEFAULT NULL,
`STATUS` VARCHAR(7) NULL DEFAULT NULL,
PRIMARY KEY (`NOPOL`),
INDEX `pkk_idx` (`NAMA_CUSTOMER` ASC, `NID_C` ASC),
CONSTRAINT `FK_NID_C`
FOREIGN KEY (`NAMA_CUSTOMER` , `NID_C`)
REFERENCES `BengkelBiru`.`customer` (`NID_C` , `NID_C`)
ON DELETE NO ACTION
ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
SQL script execution finished: statements: 14 succeeded, 1 failed
Fetching back view definitions in final form.
Nothing to fetch
Your problem is on one or both of these lines:
FOREIGN KEY (`NAMA_CUSTOMER` , `NID_C`)
REFERENCES `BengkelBiru`.`customer` (`NID_C` , `NID_C`)
^^^^^^^ Looks wrong s/b NAMA_CUSTOMER
I think you want this line:
REFERENCES `BengkelBiru`.`customer` (`NID_C` , `NID_C`)
to be
REFERENCES `BengkelBiru`.`customer` (`NAMA_CUSTOMER`, `NID_C`)
Why are you referring to NID_C twice in the reference? I say this because you define the foreign key as:
FOREIGN KEY (`NAMA_CUSTOMER` , `NID_C`)
and your descriptions at the top shows customer having NID_C and NAMA_CUSTOMER as columns.
However, fundamentally, why do you have Nama_customer in the kendaraan (vehicle) table at all? This doesn't seem to be 3rd normal form. You've repeated the customer name in a second table; which isn't part of the Customer's PK. Now, this may be acceptable if you want to keep the name of the customer at the time the entry is made into kendaraan; but since you're making it part of the FK... and doing cascade update/delete... it's very odd.
So maybe you just want:
FOREIGN KEY (`NID_C`)
REFERENCES `BengkelBiru`.`customer` (`NID_C`)
Assuming the Primary Key of Customer is NID_C
I dont think you can declare both at the same time. Try doing them separately.
CONSTRAINT `FK_NAMA_CUSTOMER`
FOREIGN KEY (`NAMA_CUSTOMER`)
REFERENCES `BengkelBiru`.`customer` (`NID_C`)
CONSTRAINT `FK_NID_C`
FOREIGN KEY (`NID_C`)
REFERENCES `BengkelBiru`.`customer` (`NID_C`)
There could be any possible scenario :-
1.Columns in the parent tables Can be INT UNSIGNED?
2.Data type in both tables should be same.
3.You are trying to reference a nonexistent key on the target table. Make sure that it is a key on the other table (it can be a primary or unique key).
Foregin Key Constaints
While creating 2 tables in phpmyadmin I am getting an error like this.
MySQL said: Documentation
#1215 - Cannot add foreign key constraint
My table structures are
CREATE TABLE `iwd_storelocator_manufacturer` (
`entity_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT ,
`name` varchar(255) NOT NULL ,
`code` varchar(255) NOT NULL ,
`grayscale_image` varchar(255) NULL ,
`color_image` varchar(255) NULL ,
PRIMARY KEY (`entity_id`)
);
CREATE TABLE `iwd_storelocator_manufacturer_to_store` (
`manufacturer_id` int(11) UNSIGNED NOT NULL ,
`store_id` int(11) NOT NULL ,
`preferred` int NULL ,
PRIMARY KEY (`manufacturer_id`, `store_id`),
FOREIGN KEY (`store_id`) REFERENCES `iwd_storelocator_store` (`store_id`) ON DELETE RESTRICT ON UPDATE CASCADE,
FOREIGN KEY (`manufacturer_id`) REFERENCES `iwd_storelocator_manufacturer` (`entity_id`) ON DELETE RESTRICT ON UPDATE CASCADE
);
Can you tell me whats the problem in it?
This is my iwd_storelocator_store table
iwd_storelocator_store
In order to know exactly what is wrong, you must check in LATEST FOREIGN KEY ERROR section.
Use this query to find this out:
SHOW ENGINE INNODB STATUS
Also, make sure that all the data types are the same: the data type of the child column must match the data type from the parent column.
If the problem is the order of creation of the tables (which can cause this error), just run set foreign_key_checks=0 so you can create the tables in any order rather than having to create all the parents tables BEFORE the child tables.
Finally, make sure that the encoding is the same for all the tables.
EDIT: in your case, you should also give us the structure of iwd_storelocator_store table
Now that we have your iwd_storelocator_store table, I think that you should create an index on store_id column as it is not the primary key of the table
I was working on creating some tables in database foo, but every time I end up with errno 150 regarding the foreign key. Firstly, here's my code for creating tables:
CREATE TABLE Clients
(
client_id CHAR(10) NOT NULL ,
client_name CHAR(50) NOT NULL ,
provisional_license_num CHAR(50) NOT NULL ,
client_address CHAR(50) NULL ,
client_city CHAR(50) NULL ,
client_county CHAR(50) NULL ,
client_zip CHAR(10) NULL ,
client_phone INT NULL ,
client_email CHAR(255) NULL ,
client_dob DATETIME NULL ,
test_attempts INT NULL
);
CREATE TABLE Applications
(
application_id CHAR(10) NOT NULL ,
office_id INT NOT NULL ,
client_id CHAR(10) NOT NULL ,
instructor_id CHAR(10) NOT NULL ,
car_id CHAR(10) NOT NULL ,
application_date DATETIME NULL
);
CREATE TABLE Instructors
(
instructor_id CHAR(10) NOT NULL ,
office_id INT NOT NULL ,
instructor_name CHAR(50) NOT NULL ,
instructor_address CHAR(50) NULL ,
instructor_city CHAR(50) NULL ,
instructor_county CHAR(50) NULL ,
instructor_zip CHAR(10) NULL ,
instructor_phone INT NULL ,
instructor_email CHAR(255) NULL ,
instructor_dob DATETIME NULL ,
lessons_given INT NULL
);
CREATE TABLE Cars
(
car_id CHAR(10) NOT NULL ,
office_id INT NOT NULL ,
engine_serial_num CHAR(10) NULL ,
registration_num CHAR(10) NULL ,
car_make CHAR(50) NULL ,
car_model CHAR(50) NULL
);
CREATE TABLE Offices
(
office_id INT NOT NULL ,
office_address CHAR(50) NULL ,
office_city CHAR(50) NULL ,
office_County CHAR(50) NULL ,
office_zip CHAR(10) NULL ,
office_phone INT NULL ,
office_email CHAR(255) NULL
);
CREATE TABLE Lessons
(
lesson_num INT NOT NULL ,
client_id CHAR(10) NOT NULL ,
date DATETIME NOT NULL ,
time DATETIME NOT NULL ,
milegage_used DECIMAL(5, 2) NULL ,
progress CHAR(50) NULL
);
CREATE TABLE DrivingTests
(
test_num INT NOT NULL ,
client_id CHAR(10) NOT NULL ,
test_date DATETIME NOT NULL ,
seat_num INT NOT NULL ,
score INT NULL ,
test_notes CHAR(255) NULL
);
ALTER TABLE Clients ADD PRIMARY KEY (client_id);
ALTER TABLE Applications ADD PRIMARY KEY (application_id);
ALTER TABLE Instructors ADD PRIMARY KEY (instructor_id);
ALTER TABLE Offices ADD PRIMARY KEY (office_id);
ALTER TABLE Lessons ADD PRIMARY KEY (lesson_num);
ALTER TABLE DrivingTests ADD PRIMARY KEY (test_num);
ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Offices FOREIGN KEY (office_id) REFERENCES Offices (office_id);
ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Clients FOREIGN KEY (client_id) REFERENCES Clients (client_id);
ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Instructors FOREIGN KEY (instructor_id) REFERENCES Instructors (instructor_id);
ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Cars FOREIGN KEY (car_id) REFERENCES Cars (car_id);
ALTER TABLE Lessons ADD CONSTRAINT FK_Lessons_Clients FOREIGN KEY (client_id) REFERENCES Clients (client_id);
ALTER TABLE Cars ADD CONSTRAINT FK_Cars_Offices FOREIGN KEY (office_id) REFERENCES Offices (office_id);
ALTER TABLE Clients ADD CONSTRAINT FK_DrivingTests_Clients FOREIGN KEY (client_id) REFERENCES Clients (client_id);
These are the errors that I get:
mysql> ALTER TABLE Applications ADD CONSTRAINT FK_Applications_Cars FOREIGN KEY
(car_id) REFERENCES Cars (car_id);
ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)
I ran SHOW ENGINE INNODB STATUS which gives a more detailed error description:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
100509 20:59:49 Error in foreign key constraint of table foo/#sql-12c_4:
FOREIGN KEY (car_id) REFERENCES Cars (car_id):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
------------
I searched around on StackOverflow and elsewhere online - came across a helpful blog post here with pointers on how to resolve this error - but I can't figure out what's going wrong. Any help would be appreciated!
You should make car_id a primary key in cars.
Note: I had the same problem, and it was because the referenced field was in a different collation in the 2 different tables (they had exact same type).
Make sure all your referenced fields have the same type AND the same collation!
Check that BOTH tables have the same ENGINE. For example if you have:
CREATE Table FOO ();
and:
CREATE Table BAR () ENGINE=INNODB;
If you try to create a constraint from table BAR to table FOO, it will not work on certain MySQL versions.
Fix the issue by following:
CREATE Table FOO () ENGINE=INNODB;
Subtle, but this error got me because I forgot to declare a smallint column as unsigned to match the referenced, existing table which was "smallint unsigned." Having one unsigned and one not unsigned caused MySQL to prevent the foreign key from being created on the new table.
id smallint(3) not null
does not match, for the sake of foreign keys,
id smallint(3) unsigned not null
I got this completely worthless and uninformative error when I tried to:
ALTER TABLE `comments` ADD CONSTRAINT FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE;
My problem was in my comments table, user_id was defined as:
`user_id` int(10) unsigned NOT NULL
So... in my case, the problem was with the conflict between NOT NULL, and ON DELETE SET NULL.
Also both the tables need to have same character set.
for e.g.
CREATE TABLE1 (
FIELD1 VARCHAR(100) NOT NULL PRIMARY KEY,
FIELD2 VARCHAR(100) NOT NULL
)ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_bin;
to
CREATE TABLE2 (
Field3 varchar(64) NOT NULL PRIMARY KEY,
Field4 varchar(64) NOT NULL,
CONSTRAINT FORIGEN KEY (Field3) REFERENCES TABLE1(FIELD1)
) ENGINE=InnoDB;
Will fail because they have different charsets. This is another subtle failure where mysql returns same error.
I use Ubuntu linux, and in my case the error was caused by incorrect statement syntax (which I found out by typing perror 150 at the terminal, which gives
MySQL error code 150: Foreign key constraint is incorrectly formed
Changing the syntax of the query from
alter table scale add constraint foreign key (year_id) references year.id;
to
alter table scale add constraint foreign key (year_id) references year(id);
fixed it.
The referenced field must be a "Key" in the referenced table, not necessarily a primary key. So the "car_id" should either be a primary key or be defined with NOT NULL and UNIQUE constraints in the "Cars" table.
And moreover, both fields must be of the same type and collation.
I also received this error (for several tables) along with constraint errors and MySQL connecting and disconnecting when attempting to import an entire database (~800 MB). My issue was the result of The MySQL server max allowed packets being too low. To resolve this (on a Mac):
Opened /private/etc/my.conf
Under # The MySQL server, changed max_allowed_packet from 1M to 4M (You may need to experiment with this value.)
Restarted MySQL
The database imported successfully after that.
Note I am running MySQL 5.5.12 for Mac OS X (x86 64 bit).
check to make the field you are referencing to is an exact match with foreign key, in my case one was unsigned and the other was signed so i just changed them to match and this worked
ALTER TABLE customer_information
ADD CONSTRAINT fk_customer_information1
FOREIGN KEY (user_id)
REFERENCES users(id)
ON DELETE CASCADE
ON UPDATE CASCADE
Solved:
Check to make sure Primary_Key and Foreign_Key are exact match with data types.
If one is signed another one unsigned, it will be failed.
Good practice is to make sure both are unsigned int.
I was using a duplicate Foreign Key Name.
Renaming the FK name solved my problem.
Clarification:
Both tables had a constraint called PK1, FK1, etc. Renaming them/making the names unique solved the problem.
The referenced column must be an index of a single column or the first column in multi column index, and the same type and the same collation.
My two tables have the different collations. It can be shown by issuing show table status like table_name and collation can be changed by issuing alter table table_name convert to character set utf8.
all, I solved a problem and wanted to share it:
I had this error <>
The issue was in that in my statement:
alter table system_registro_de_modificacion add foreign key
(usuariomodificador_id) REFERENCES Usuario(id) On delete restrict;
I had incorrectly written the CASING: it works in Windows WAMP, but in Linux MySQL it is more strict with the CASING, so writting "Usuario" instead of "usuario" (exact casing), generated the error, and was corrected simply changing the casing.
When I execute the follow two queries (I have stripped them down to absolutely necessary):
mysql> CREATE TABLE foo(id INT PRIMARY KEY);
Query OK, 0 rows affected (0.01 sec)
mysql> CREATE TABLE bar ( id INT, ref INT, FOREIGN KEY (ref) REFERENCES foo(id)) ENGINE InnoDB;
I get the following error:
ERROR 1005 (HY000): Can't create table './test/bar.frm' (errno: 150)
Where the **** is my error? I haven't found him while staring at this for half an hour.
From FOREIGN KEY Constraints
If you re-create a table that was
dropped, it must have a definition
that conforms to the foreign key
constraints referencing it. It must
have the right column names and types,
and it must have indexes on the
referenced keys, as stated earlier. If
these are not satisfied, MySQL returns
error number 1005 and refers to error
150 in the error message.
My suspicion is that it's because you didn't create foo as InnoDB, as everything else looks OK.
Edit: from the same page -
Both tables must be InnoDB tables and they must not be TEMPORARY tables.
You can use the command SHOW ENGINE INNODB STATUS to get more specific information about the error.
It will give you a result with a Status column containing a lot of text.
Look for the section called LATEST FOREIGN KEY ERROR which could for example look like this:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
190215 11:51:26 Error in foreign key constraint of table `mydb1`.`contacts`:
Create table `mydb1`.`contacts` with foreign key constraint failed. You have defined a SET NULL condition but column 'domain_id' is defined as NOT NULL in ' FOREIGN KEY (domain_id) REFERENCES domains (id) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT contacts_teams_id_fk FOREIGN KEY (team_id) REFERENCES teams (id) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT' near ' ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT contacts_teams_id_fk FOREIGN KEY (team_id) REFERENCES teams (id) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT'.
To create a foreign key ,
both the main column and the reference column must have same definition.
both tables engine must be InnoDB.
You can alter the engine of table using this command , please take the backup before executing this command.
alter table [table name] ENGINE=InnoDB;
I had the same problem, for those who are having this also:
check the table name of the referenced table
I had forgotten the 's' at the end of my table name
eg table Client --> Clients
:)
Apart form many other reasons to end up with MySql Error 150 (while using InnoDB), One of the probable reason, is the undefined KEY in the create statement of the table containing the column name referenced as a foreign key in the relative table.
Let's say the create statement of master table is -
CREATE TABLE 'master_table' (
'id' int(10) NOT NULL AUTO_INCREMENT,
'record_id' char(10) NOT NULL,
'name' varchar(50) NOT NULL DEFAULT '',
'address' varchar(200) NOT NULL DEFAULT '',
PRIMARY KEY ('id')
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and the create syntax for the relative_table table where the foreign key constraint is set from primary table -
CREATE TABLE 'relative_table' (
'id' int(10) NOT NULL AUTO_INCREMENT,
'salary' int(10) NOT NULL DEFAULT '',
'grade' char(2) NOT NULL DEFAULT '',
'record_id' char(10) DEFAULT NULL,
PRIMARY KEY ('id'),
CONSTRAINT 'fk_slave_master' FOREIGN KEY ('record_id') REFERENCES 'master' ('record_id')
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
This script is definitely going to end with MySql Error 150 if using InnoDB.
To solve this, we need to add a KEY for the The column record_id in the master_table table and then reference in the relative_table table to be used as a foreign_key.
Finally, the create statement for the master_table, will be -
CREATE TABLE 'master_table' (
'id' int(10) NOT NULL AUTO_INCREMENT,
'record_id' char(10) NOT NULL,
'name' varchar(50) NOT NULL DEFAULT '',
'address' varchar(200) NOT NULL DEFAULT '',
PRIMARY KEY ('id'),
KEY 'record_id' ('record_id')
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I had very same problem and the reason was the "collation" of columns was different. One was latin1 while the other was utf8
This may also happen if you have not given correct column name after "references" keyword.