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.
我有两个表,有一个ID的PK,如果我删除ID = 1的条目,我希望它能自动删除另一个表中的ID FK。换句话说,我希望它也应该删除其他表中ID = 1的所有条目。我该怎么做呢?我已经链接了PK-FK关系,但是当我在PK表中删除ID 1的条目时,它不会删除FK。
2 个解决方案
#1
4
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:
确保您使用的是两个表的InnoDB引擎,并在delete cascade中添加一个外键约束。您的表创建SQL应该是这样的:
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.
其中child_table和parent_table是子表和父表的名称。
#2
0
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.
注意:您需要使用InnoDB存储引擎,他默认MyISAM存储引擎不支持外键关系。
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
)
#1
4
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:
确保您使用的是两个表的InnoDB引擎,并在delete cascade中添加一个外键约束。您的表创建SQL应该是这样的:
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.
其中child_table和parent_table是子表和父表的名称。
#2
0
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.
注意:您需要使用InnoDB存储引擎,他默认MyISAM存储引擎不支持外键关系。
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
)