gpt4 book ai didi

php - 如何使用 php pdo 从 mysql 中具有外键约束的数据库中删除数据

转载 作者:行者123 更新时间:2023-11-29 10:12:27 25 4
gpt4 key购买 nike

我的数据库中有三个表。

表1

项目

PK ProjectID

表2

学生

PK RegNo
FK ProjectID

表3

进展

FK RegNo

现在我想要执行删除操作,当我从项目中删除记录时,应该从学生中删除它,因为学生主键也作为外键进度表存在,所以它也应该从进度表中删除 RegNo 。我如何才能以最好的方式实现这一目标。提前致谢。

$query = "DELETE students, progress from students inner join progress on progress.RegNo=students.RegNo where students.ProjectID='$id';DELETE FROM projects where projects.ProjectID='$id'";

//$conn->exec($query);
$stmt = $conn->prepare($query);
$stmt->execute();

它违反了外键约束

最佳答案

将删除拆分为单独的查询可能会更容易。

 DELETE FROM `progress` 
WHERE `RegNo` IN(
SELECT `RegNo` FROM `students` WHERE ProjectID = '$id'
);

DELETE FROM `student` WHERE `ProjectID` = '$id';
DELETE FROM `projects` WHERE `ProjectID` = '$id';

关于php - 如何使用 php pdo 从 mysql 中具有外键约束的数据库中删除数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50740210/

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