Create new column with foreign key into table error - mysql

I have a problem with creating a new branch_id column in the table tn_whatsapp.
Below are my SQL queries steps :
1. ALTER TABLE tn_whatsapp ADD branch_id varchar(40) NOT NULL AFTER tenant_id;
2. ALTER TABLE `tn_whatsapp` CHANGE COLUMN `branch_id` `branch_id` VARCHAR(40) NOT NULL COLLATE 'utf8mb4_unicode_ci' AFTER `tenant_id`;
3. ALTER TABLE `tn_whatsapp` ADD CONSTRAINT `ibfk_branch_id` FOREIGN KEY (`branch_id`) REFERENCES `tn_branch` (`id`) ON UPDATE CASCADE ON DELETE CASCADE;
Only in Step 3 query cannot add a foreign key and the error messages show -
SQL Error (3780): Referencing column 'branch_id' and referenced column 'id' in foreign key constraint 'ibfk_branch_id' are incompatible.
This is my tn_whatapps table structure:
This is my tn_branch table structure, id is branch_id in the tn_whatsapp table
I want the expected result like the below picture:
I am using HeidiSQL - version 12.0.0.6468
I have followed this StackOverflow answer ERROR 3780: Referencing column and referenced column in foreign key constraint are incompatible also cannot solve my problem.
May I know which parts I am getting wrong in step 3? Thanks.

Related

Cannot create table mysql(mariadb). Table is corrupted

Some how, my database has gotten into a bad state. I previously had a table named live_stream. When I tried to drop a foreign key constraint, I got an error that mariadb could not rename #sql-26_e7a to live_stream. Now when I try to run the following statement, I get this error.
Can't create table live_stream (errno: 150 "Foreign key constraint is incorrectly formed")
CREATE TABLE live_stream
(idbigint(20) NOT NULL PRIMARY KEY);
As you can see I don't have any foreign key constraints in the definition. If I try the exact same definition with a different table name, it works. If I try to drop the table, mariadb complains that live_stream doesn't exist. Its like the table or foreign key are stuck in a transaction or something like that.
I am using galara with maria db 10.3.
UPDATE
I believe the problem was introduced when a foreign key and unique index were given the same name. I recreated the scenario, and when I try to drop the index, mariadb prevents it.
* UPDATE 2 *
Here is the output of SHOW ENGINE INNODB STATUS;
* UPDATE3 *
Here are the steps to reproduce.
create table tb1
(
id bigint null,
constraint tb1_pk
primary key (id)
);
create table tb2
(
id bigint null,
tb1_id bigint null,
constraint tb2_pk
primary key (id),
constraint tb2_tb1_id_fk
foreign key (tb1_id) references tb1 (id)
);
ALTER TABLE tb2 ADD CONSTRAINT tb2_tb1_id_fk UNIQUE (tb1_id, tb1_id);
drop index tb2_tb1_id_fk on tb2;
The problem is that the unique constraint has the same name as the foreign key and references the same column twice.

MySQL Altering a Table with Foreign Key

So I've tried to do this a number of ways. Basically I'm given the following instructions:
Using the blog database (use either a single-line or a multi-line SQL statement):
Write a SQL ALTER TABLE statement that adds a post_id column to the blog.comments table.
This new column should be an INTEGER data type with a max. size of 3 digits, UNSIGNED, it should be NOT NULL and it should work as a FOREIGN KEY that uses as a reference the id column of the blog.posts table.
I have no issue adding the column, it's getting the foreign key to work that's stumping me. I used the following code:
ALTER TABLE blog.comments
ADD COLUMN post_id INT(3) UNSIGNED NOT NULL;
ALTER TABLE blog.comments
ADD FOREIGN KEY (post_id) REFERENCES posts(id);
And I keep getting the following error when I submit it:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (b
log.#sql-628_2a, CONSTRAINT #sql-628_2a_ibfk_1 FOREIGN KEY (post_id) REFERENCES
posts (id))
I have tried several different versions but I can't get it to work.

MySQL add Foreign Key

I want to update a column which is currently a plain INT(16) so that it references a FK on another table. I've tried the following, but with errors:
ALTER TABLE ts_keys ADD CONSTRAINT FK_account_id FOREIGN KEY (account_id) REFERENCES accounts(id) ON UPDATE CASCADE ON DELETE CASCADE
EDIT: Sorry, forgot to add the error:
Can't create table (errno: 150)
Both tables are Innodb.
EDIT 2: I also tried re-creating the table but same error:
CREATE TABLE ts_keys (
id int PRIMARY KEY AUTO_INCREMENT,
account_id int,
FOREIGN KEY fk_account_id1(account_id) REFERENCES accounts(id)
) ENGINE=InnoDB;
The datatype of the foreign key column must match EXACTLY the datatype of the referenced column.
Do a SHOW CREATE TABLE accounts and look at the definition of the id column.
Whatever that column is defined as INT UNSIGNED, BIGINT, VARCHAR(16), whatever,
the column you want to define as a foreign key (the account_id column in ts_keys table) must match that datatype EXACTLY. (It's just the datatype that has to match. The column comment doesn't have to match, the DEFAULT value doesn't have to match, the NULL/NOT NULL doesn't have to match. But it's required that the datatypes match.
Your syntax for adding the constraint looks correct:
ALTER TABLE ts_keys
ADD CONSTRAINT FK_account_id
FOREIGN KEY (account_id)
REFERENCES accounts(id)
ON UPDATE CASCADE ON DELETE CASCADE
Admittedly, the "Can't create table (errno: 150)" has to be the least helpful message regarding what's actually causing the problem. (At least the error isn't the "check the manual" syntax error.

unable to drop the foreign key

I would like to drop the foreign key in my table but been into this error message
mysql> alter table customers drop foreign key customerid;
ERROR 1025 (HY000): Error on rename of '.\products\customers' to '.\products\#sql2-7ec-a3' (errno: 152)
mysql>
The solution described here by Chris White worked for me.
The root problem is that MySQL creates both an index and a foreign key. Both must be removed (the foreign key first contrary to what Chris said).
show create table table_name;
SHOW CREATE TABLE `table_name`:
| table_name | CREATE TABLE `table_name` (
`id` int(20) unsigned NOT NULL auto_increment,
`key_column` smallint(5) unsigned default '1',
KEY `column_tablein_26440ee6` (`key_column`), <--- shows key name
CONSTRAINT `table_name_ibfk_1` FOREIGN KEY (`key_column`) REFERENCES <--- shows foreign key constraint name
`second_table` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
Delete the foreign key constraint:
ALTER TABLE table_name DROP FOREIGN KEY `table_name_ibfk_1`;
Delete the key
ALTER TABLE table_name DROP KEY `column_tablein_26440ee6`;
That did it for me.
It looks like a bug in the error messaging of MySQL. (http://bugs.mysql.com/bug.php?id=10333)
Use SHOW CREATE TABLE table_name to see the actual name of the foreign key. It looks like it might be mysql query browser problem when generating the query with wrong spelling of the foreign key name.
To avoid getting this error while trying to drop a foreign key, use the constraint name rather than the column name of the foreign key.
When I tried
mysql> ALTER TABLE mytable DROP PRIMARY KEY;
I got error as
ERROR 1025 (HY000): Error on rename of '.\database\#sql-454_3' to '.\database\mytable' (errno: 150).
I solved it using:
mysql> ALTER TABLE mytable DROP PRIMARY KEY, ADD PRIMARY KEY (column1,column2,column3);
Some links that will help you.
link 1
link 2 [look for Posted by Alex Blume on November 7 2008 5:09pm & Posted by Hector Delgadillo on January 21 2011 4:57am]
To avoid getting this error while trying to drop a foreign key, use the constraint name rather than the column name of the foreign key
You should try with the foreign key name as Fahim Parkar suggested. Actually that does not work always either.
In my case I used the
FOREIGN KEY `fk`(`col1`) REFERENCES `table2`(`col1`)
code to add the fk by creation.
The problem with this code that it is not valid and should throw some kind of syntax error, but still it added a foreign key with a random name.
When I added the fk with the right syntax:
CONSTRAINT `fk` FOREIGN KEY (`col1`) REFERENCES `table2`(`col1`)
the following code dropped it properly:
ALTER TABLE `table1` DROP FOREIGN KEY `fk`
So this kind of error can happen too if you try to remove a foreign key with an invalid name. It is important to view the table properties with
SHOW CREATE TABLE `table1`
and check the foreign key names if you get this kind of errors.

Add Foreign Key to existing table

I want to add a Foreign Key to a table called "katalog".
ALTER TABLE katalog
ADD CONSTRAINT `fk_katalog_sprache`
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL;
When I try to do this, I get this error message:
Error Code: 1005. Can't create table 'mytable.#sql-7fb1_7d3a' (errno: 150)
Error in INNODB Status:
120405 14:02:57 Error in foreign key constraint of table
mytable.#sql-7fb1_7d3a:
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL:
Cannot resolve table name close to:
(`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL
When i use this query it works, but with wrong "on delete" action:
ALTER TABLE `katalog`
ADD FOREIGN KEY (`Sprache` ) REFERENCES `sprache` (`ID` )
Both tables are InnoDB and both fields are "INT(11) not null". I'm using MySQL 5.1.61. Trying to fire this ALTER Query with MySQL Workbench (newest) on a MacBook Pro.
Table Create Statements:
CREATE TABLE `katalog` (
`ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`AnzahlSeiten` int(4) unsigned NOT NULL,
`Sprache` int(11) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `katalogname_uq` (`Name`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC$$
CREATE TABLE `sprache` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Bezeichnung` varchar(45) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `Bezeichnung_UNIQUE` (`Bezeichnung`),
KEY `ix_sprache_id` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
To add a foreign key (grade_id) to an existing table (users), follow the following steps:
ALTER TABLE users ADD grade_id SMALLINT UNSIGNED NOT NULL DEFAULT 0;
ALTER TABLE users ADD CONSTRAINT fk_grade_id FOREIGN KEY (grade_id) REFERENCES grades(id);
Simply use this query, I have tried it as per my scenario and it works well
ALTER TABLE katalog ADD FOREIGN KEY (`Sprache`) REFERENCES Sprache(`ID`);
Simple Steps...
ALTER TABLE t_name1 ADD FOREIGN KEY (column_name) REFERENCES t_name2(column_name)
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL;
But your table has:
CREATE TABLE `katalog` (
`Sprache` int(11) NOT NULL,
It cant set the column Sprache to NULL because it is defined as NOT NULL.
check this link. It has helped me with errno 150:
http://verysimple.com/2006/10/22/mysql-error-number-1005-cant-create-table-mydbsql-328_45frm-errno-150/
On the top of my head two things come to mind.
Is your foreign key index a unique name in the whole database (#3 in the list)?
Are you trying to set the table PK to NULL on update (#5 in the list)?
I'm guessing the problem is with the set NULL on update (if my brains aren't on backwards today as they so often are...).
Edit: I missed the comments on your original post. Unsigned/not unsigned int columns maybe resolved your case. Hope my link helps someone in the future thought.
How to fix Error Code: 1005. Can't create table 'mytable.#sql-7fb1_7d3a' (errno: 150) in mysql.
alter your table and add an index to it..
ALTER TABLE users ADD INDEX index_name (index_column)
Now add the constraint
ALTER TABLE foreign_key_table
ADD CONSTRAINT foreign_key_name FOREIGN KEY (foreign_key_column)
REFERENCES primary_key_table (primary_key_column) ON DELETE NO ACTION
ON UPDATE CASCADE;
Note if you don't add an index it wont work.
After battling with it for about 6 hours I came up with the solution
I hope this save a soul.
MySQL will execute this query:
ALTER TABLE `db`.`table1`
ADD COLUMN `col_table2_fk` INT UNSIGNED NULL,
ADD INDEX `col_table2_fk_idx` (`col_table2_fk` ASC),
ADD CONSTRAINT `col_table2_fk1`
FOREIGN KEY (`col_table2_fk`)
REFERENCES `db`.`table2` (`table2_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
Cheers!
When you add a foreign key constraint to a table using ALTER TABLE, remember to create the required indexes first.
Create index
Alter table
try all in one query
ALTER TABLE users ADD grade_id SMALLINT UNSIGNED NOT NULL DEFAULT 0,
ADD CONSTRAINT fk_grade_id FOREIGN KEY (grade_id) REFERENCES grades(id);
step 1: run this script
SET FOREIGN_KEY_CHECKS=0;
step 2: add column
ALTER TABLE mileage_unit ADD COLUMN COMPANY_ID BIGINT(20) NOT NULL
step 3: add foreign key to the added column
ALTER TABLE mileage_unit
ADD FOREIGN KEY (COMPANY_ID) REFERENCES company_mst(COMPANY_ID);
step 4: run this script
SET FOREIGN_KEY_CHECKS=1;
ALTER TABLE child_table_name ADD FOREIGN KEY (child_table_column) REFERENCES parent_table_name(parent_table_column);
child_table_name is that table in which we want to add constraint.
child_table_column is that table column in which we want to add foreign key.
parent table is that table from which we want to take reference.
parent_table_column is column name of the parent table from which we take reference
this is basically happens because your tables are in two different charsets. as a example one table created in charset=utf-8 and other tables is created in CHARSET=latin1 so you want be able add foriegn key to these tables. use same charset in both tables then you will be able to add foriegn keys. error 1005 foriegn key constraint incorrectly formed can resolve from this
The foreign key constraint must be the same data type as the primary key in the reference table and column
ALTER TABLE TABLENAME ADD FOREIGN KEY (Column Name) REFERENCES TableName(column name)
Example:-
ALTER TABLE Department ADD FOREIGN KEY (EmployeeId) REFERENCES Employee(EmployeeId)
i geted through the same problem. I my case the table already have data and there were key in this table that was not present in the reference table. So i had to delete this rows that disrespect the constraints and everything worked.
Double check if the engine and charset of the both tables are the same.
If not, it will show this error.