我有这样的表结构:
PrimaryTable
- > p_id
此处p_id是主要
SecondoryTable
- > s_id
p_id
此处p_id是外键
ThirdTable
- > t_id
s_id
此处s_id是外键
FourthTable
- > f_id
t_id
此处t_id是外键
因此,我要从p_id
删除我的PrimaryTable
之一并希望其SecondoryTable
数据也应删除,ThirdTable
数据应删除{SecondoryTable
应参考FourthTable
ThirdTable
数据
我知道我可以从下到上编写Delete
查询,但是如何处理这么多级别?
我发现了这个但不确定如何:https://stackoverflow.com/a/9847308/1182021
因为它的四级层次结构我很困惑。
EDIT1:
如果要在删除Primary
Child
该怎么办?
请建议。
答案 0 :(得分:1)
根据OP的请求,这是当用户想要从子表中删除行时从父表中删除行的情况的答案。删除父项时递归删除所有子项的情况正在使用MySQL ON DELETE CASCADE选项。
4个表格是table1,table2,table3&表4
如果用户想要删除table2中的行以及table1中的相应行(table2的父级),那么在PHP中:
// t2_delete_row_id is the id of the table 2 row to be deleted
// get the the parent of table2
$sql_get_parent = "select p_id from table2 where s_id = 't2_delete_row_id '";
// execute this query using MySQLi/PDO to get id of the parent row to be deleted
// assuming that id is t1_parent_row_id
// now delete the row from table 2:
// note that because of the foreign key constraints,
// corresponding rows from table3 and table4 would also be deleted
$sql_delete_child = "delete from table2 where s_id = 't2_delete_row_id'";
if (mysqli_query($sql_delete_child)){
// delete the parent row
$sql_delete_parent = "delete from table1 where p_id = 't1_parent_row_id'";
}
可以扩展此逻辑,以便在删除table3行时,也会删除相应的父(table2)和“grand-parent”(table1)行。这种情况可能需要一些递归。当然,由于外键约束,这当然会删除table4中的子行。
答案 1 :(得分:0)
如果您无法使用FOREIGN KEYS(即使用MyISAM表),我会为此创建一个TRIGGER。下面第一个示例...您将需要为每个级联的表创建一个。
DELIMITER //
CREATE TRIGGER `pDeleteTrigger` BEFORE DELETE ON `PrimaryTable`
FOR EACH ROW BEGIN
DELETE FROM `SecondoryTable` WHERE NEW.`p_id` = `SecondoryTable`.`p_id`
END
//
DELIMITER ;
答案 2 :(得分:0)
我脑子里有两种方法(如果你的语言是Tsql)
1.-存储程序
这个想法是有一个程序“spDelete_PrimaryTable”,这样你就可以通过在tsql中写一些东西来删除四个表中的寄存器,如:
exec spDelete_PrimaryTable
@p_id= 25 /* (25 or watever p_id of primary table you want to delete)*/
(是的,你可以从你想要的vb.net或watever中调用它。)
代码如下:
use [your_database]
CREATE PROCEDURE [dbo].[spDelete_PrimaryTable]
@p_id nvarchar(MAX)
AS
begin
SET NOCOUNT ON;
delete from FourthTable where t_id in (
select ThirdTable.t_id
from ThirdTable inner join SecondoryTable on ThirdTable.s_id = SecondoryTable.s_id
where SecondoryTable.p_id = @p_id
)
go
delete from ThirdTable where s_id in (
select SecondoryTable.s_id
where SecondoryTable.p_id = @p_id
)
go
/*Lol, I forgot to eliminate from the "SecondoryTable" */
delete from SecondoryTable.s_id
where SecondoryTable.p_id = @p_id
go
delete from PrimaryTable where p_id = @p_id
go
END
GO
2.-触发
似乎“克里斯托弗·莫里西”已经发布了我正在编辑这个答案的XP