Unable to update/delete/truncate table with foreign key - mysql

I have 2 tables
CREATE TABLE table1 (
id1 int(10) NOT NULL PRIMARY KEY,
name varchar(20)
);
CREATE TABLE table2 (
newid int(10) NOT NULL PRIMARY KEY,
f_id int(10)
);
Now, I have added a foreign key constrain
ALTER TABLE table2
ADD CONSTRAINT fk_id FOREIGN KEY (f_id) REFERENCES table1 (id)
ON DELETE CASCADE ON UPDATE CASCADE;
Now, the problem is I am unable to update/delete/truncate the table 'table2'. What is the exact problem here and how to solve it?

Foreign key enforces referential integrity,try to remove the record from table 1 and then table 2. You cannot truncate a table which is having FK

Related

How to create a table with a composite key made of 2 foreign keys referencing to other tables?

I have three tables A, B and funding:
Table A has a primary key partner_id
Table B has a primary key branch_id
When I try to create table C with the following code:
CREATE TABLE Funding (
partner_id INT,
branch_id INT,
total_fund FLOAT,
PRIMARY KEY (partners_id, branch_id),
FOREIGN KEY (partners_id) REFERENCES A(partner_id) ON delete SET NULL,
FOREIGN KEY (branch_id) REFERENCES B(branch_id) ON delete SET NULL
);
I get error message:
1830: column partner_id cannot be NOT NULL: needed in a foreign key constraint.
How can I solve this problem?
Create a separted ID for PK:
SQL DEMO
CREATE TABLE A (
partner_id INT,
PRIMARY KEY (partner_id)
);
CREATE TABLE B (
branch_id INT,
PRIMARY KEY (branch_id)
);
CREATE TABLE Funding (
id INT PRIMARY KEY AUTO_INCREMENT,
partner_id INT,
branch_id INT,
total_fund FLOAT,
FOREIGN KEY (partner_id) REFERENCES A(partner_id) ON DELETE SET NULL,
FOREIGN KEY (branch_id) REFERENCES B(branch_id) ON DELETE SET NULL
);
You can also add:
ALTER TABLE `Funding` ADD UNIQUE `unique_index`(partner_id, branch_id);
But that can cause problem when multiple partners from same branch are deleted
In CREATE TABLE Funding just add NOT NULL statement to partner_id and branch_id.
CREATE TABLE Funding ( partner_id INT NOT NULL, branch_id INT NOT NULL,...

Change value of primary key (ID of a particular record) when foreign key constraints exist

Here's the basic gist of what I'm trying to do:
create table main(id char(1) primary key);
create table other (
id int primary key auto_increment,
main_id char(1),
key m (main_id),
constraint fk foreign key (main_id) references main(id)
);
insert into main(id) values('a');
insert into other(main_id) values('a');
update main inner join other on other.main_id=main.id
set main.id='b', other.main_id='b'
where main.id='a';
This results in a foreign key constraint failure. Is there any way to accomplish this without dropping the foreign keys (not really an option on my large production database)?
You can do this simply by temporarily setting foreign_key_checks=0 in your session:
set foreign_key_checks=0;
update main inner join other on other.main_id=main.id
set main.id='b', other.main_id='b'
where main.id='a';
Another option is to configure the foreign key with the ON UPDATE CASCADE option so that if the primary key is updated on the parent table it will cascade to the child table:
create table main(id char(1) primary key);
create table other (
id int primary key auto_increment,
main_id char(1),
key m (main_id),
constraint fk foreign key (main_id) references main(id) on update cascade
);

Error in foreign key constraint on a dropped table

When I execute the following SQL commands:
CREATE TABLE `TableA` (
`tableAId` INT(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`tableAId`)
);
CREATE TABLE `TableB` (
`tableBId` INT(11) NOT NULL AUTO_INCREMENT,
`tableAId` INT(11) DEFAULT NULL,
PRIMARY KEY (`tableBId`),
CONSTRAINT `FK_TABLE_A_ID` FOREIGN KEY (`tableAId`) REFERENCES `TableA` (`tableAId`)
);
ALTER TABLE `TableB`
RENAME TO `NewTableB`;
ALTER TABLE `TableA`
RENAME TO `NewTableA`,
CHANGE COLUMN `tableAId` `newTableAId` INT(11) NOT NULL AUTO_INCREMENT FIRST;
DROP TABLE IF EXISTS NewTableA;
DROP TABLE IF EXISTS NewTableB;
CREATE TABLE `TableA` (
`tableAId` INT(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`tableAId`)
);
I have the following error on the last command (ie CREATE TABLE TableA (...)) :
Erreur SQL (1005): Can't create table 'TableA' (errno: 150) Foreign
key constraint is incorrectly formed
And when I execute show engine innodb status I have :
------------------------
LATEST FOREIGN KEY ERROR
------------------------
130531 12:06:05 Error in foreign key constraint of table TableB:
there is no index in referenced table which would contain
the columns as the first columns, or the data types in the
referenced table do not match the ones in table. Constraint:
,
CONSTRAINT `FK_TABLE_A_ID` FOREIGN KEY (`tableAId`) REFERENCES `NewTableA` (`tableAId`)
Old question but for others in a similar situation the answer I made at:
https://dba.stackexchange.com/a/87587/56052
may help.
Recreate the table with the same foreign key specification as previous but a
different name.
Drop the resulting table (will also drop original orphan foreign key)
Recreate table with original or no foreign key

Adding foreign key on multiple columns

I'm trying to create a foreign key on two columns of a table to point to the same column of another table, but I seem to get an error...
Here's what I do:
CREATE TABLE test2 (
ID INT NOT NULL AUTO_INCREMENT,
col1 INT NOT NULL,
col2 INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk FOREIGN KEY (col1, col2)
REFERENCES test1(ID, ID)
ON UPDATE CASCADE
ON DELETE RESTRICT
) ENGINE=InnoDB;
But I get
ERROR 1005 (HY000): Can't create table 'DB.test2' (errno: 150)
If I only have one column, however, the table is correctly created.
Could someone point out to me where the error is?
Thanks
n
Tried it here and got the same error. This works though:
CREATE TABLE test2 (
ID INT NOT NULL AUTO_INCREMENT,
col1 INT NOT NULL,
col2 INT NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT fk FOREIGN KEY (col1)
REFERENCES test1(ID)
ON UPDATE CASCADE
ON DELETE RESTRICT,
CONSTRAINT fk2 FOREIGN KEY (col2)
REFERENCES test1(ID)
ON UPDATE CASCADE
ON DELETE RESTRICT
) ENGINE=InnoDB
Yes, I know - your script should work (even if it doesn't seem to make much sense). Yet, I guess this new version is better.
The problem would appear to be that you are specifying the same parent column twice in the same foreign key (i.e, (ID, ID)). The following should work:
Create Table Test1
(
PK1 int not null
, PK2 int not null
, Primary Key ( PK1, PK2 )
)
Create Table Test2
(
Id int not null Auto_Increment
, PK1 int not null
, PK2 int not null
, Primary Key ( ID )
, Constraint FK_Test2
Foreign Key ( PK1, PK2 )
References Test1( PK1, PK2 )
)
If it is the case, that you want two columns in a child table referencing the same parent table column, then you must add two foreign key references as shown by rsenna as those represent two independent relations.

Mysql mapping table FK constraints

I'm experiencing some difficulties with foreign key constraints. I have three tables:
Features
ID PK AUTO_INC
Title VARCHAR
Subscriptions
ID PK AUTO_INC
Title VARCHAR
Subscriptionfeatures
ID PK AUTO_INC
feature_id INT (index)
subscription_id INT (index)
When I have the following records
Features
1 Testfeature
Subscriptions
1 Testsubscription
I can insert the following record in Subscriptionfeatures when defining a FK constraint as follows
ALTER TABLE subscriptionfeatures ADD CONSTRAINT FK_feature FOREIGN KEY (feature_id) REFERENCES features(id);
Subscriptionfeatures
x 1 1 => ok
But I can not insert the identical record when adding an ON DELETE CASCADE clause to the FK constraint, but i must admint i do not understand its reason for denial!
ALTER TABLE subscriptionfeatures ADD CONSTRAINT FK_feature FOREIGN KEY (feature_id) REFERENCES features(id) ON DELETE CASCADE;
Subscriptionfeatures
x 1 1 => fails
Any help on this would be greatly appreciated!
This works for me:
CREATE TABLE Features (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Title VARCHAR(100)
) Engine=InnoDB;
CREATE TABLE Subsriptions (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Title VARCHAR(100)
) Engine=InnoDB;
CREATE TABLE Subscriptionfeatures (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
feature_id INT NOT NULL,
subscription_id INT NOT NULL,
KEY ix_subscriptionfeatures_feature (feature_id),
KEY ix_subscriptionfeatures_subscription (subscription_id)
) Engine=InnoDB;
INSERT
INTO Features
VALUES (1, 'Testfeature');
INSERT
INTO Subsriptions
VALUES (1, 'Testsubscription');
ALTER TABLE subscriptionfeatures ADD CONSTRAINT FK_feature FOREIGN KEY (feature_id) REFERENCES features(id) ON DELETE CASCADE;
INSERT
INTO Subscriptionfeatures (feature_id, subscription_id)
VALUES (1, 1);
What is the error the MySQL gives?