gpt4 book ai didi

php - 删除主键时删除所有外键数据,反之亦然

转载 作者:行者123 更新时间:2023-11-29 13:42:33 26 4
gpt4 key购买 nike

我有这样的表结构:

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 是外键

因此,我要从 PrimaryTable 中删除我的一个 p_id,并希望其 SecondoryTable 数据也应被删除并且 ThirdTable 数据应引用SecondoryTable 删除,FourthTable 数据应引用ThirdTable 删除

我知道我可以从下到上编写Delete查询,但是对于像这样的这么多级别该怎么办?

我发现了这个,但不确定如何:https://stackoverflow.com/a/9847308/1182021

因为它的四级层次结构我很困惑。

编辑1:

如果我想在删除 Child 时删除 Primary,该怎么办

请提出建议。

最佳答案

根据OP的请求,这是针对当从子表中删除行时用户想要从父表中删除该行的情况的答案。当删除父级时递归删除所有子级的情况正在使用 MySQL ON DELETE CASCADE 选项。

这 4 个表是 table1、table2、table3 和 table4。

如果用户想要删除 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)和“祖父”(table1)行也将被删除。对于这种情况,可能需要一些递归。由于外键约束,这当然会删除 table4 中的子行。

关于php - 删除主键时删除所有外键数据,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17888590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com