开发者

delete primary key also deletes foreign key

I have two 开发者_如何学编程table, with a PK of ID. If say I delete the entry for ID = 1, I want it to automatically delete the FK of ID in the other table. In other words I want so that it should also delete all entries with ID = 1 in the other table. How can I do this? I have linked the PK-FK relationship, but when I delete the entry with ID 1 in the PK table it doesn't delete the FK.


Make sure you're using the InnoDB engine for both tables, and add a foreign-key constraint specifying on delete cascade. Your table creation SQL should look something like this:

create table child_table (
    parent_id int references parent_table(id) on delete cascade
) engine 'innodb';

where child_table and parent_table are the names of your child and parent tables.


You have to define your Foreign Key constraints as ON DELETE CASCADE.

Note: You need to use InnoDB storage engine, he default MyISAM storage engine not support foreign keys relation.

CREATE TABLE `table2` (
`id` int(11) NOT NULL auto_increment,
`name` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `ids` (`ids`)
CONSTRAINT `foreign` FOREIGN KEY (`ids`)
REFERENCES `table2` (`ids`) ON DELETE CASCADE ON UPDATE CASCADE
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜