我正在为数据库创建ADD / UPDATE / DELETE系统,在对删除查询进行编码时,我发现约束失败,阻止了我从特定行中删除某些数据。
删除查询:
if (isset($_GET['company'])) {
$id = $_GET['company'];
$query_del = " DELETE company.* , client.* , queries.*
FROM company
INNER JOIN client ON company.idcompany =
client.idcompany
INNER JOIN queries ON
client.idclient =
queries.idclient
WHERE company.idcompany = '" . $id . "'";
$result_del = mysqli_query($con, $query_del);
if ($result_del) {
header("location:companylist.php");
} else {
echo ' Erro: ' . mysqli_error($con);
}
}
所需表:
company: idcompany , company_name
client: idclient , idcompany
queries: idclient
错误:
无法删除或更新父行:外键约束失败 ({
db
。client
,约束client_ibfk_1
外部密钥(idcompany
) 参考文献company
(idcompany
)
基本上,我通过URL获取行号,并尝试删除所有三个表上与该idcompany相关的所有数据。有人知道如何在删除查询上关联所有三个表吗?
答案 0 :(得分:0)
要创建所需的表结构,我使用了以下create语句:
CREATE TABLE company (
idcompany INT,
company_name VARCHAR(31),
PRIMARY KEY (idcompany));
CREATE TABLE clients (
idclient INT,
idcompany INT,
PRIMARY KEY (idclient),
FOREIGN KEY (idcompany) REFERENCES company(idcompany) ON DELETE CASCADE);
CREATE TABLE queries (
idclient INT,
FOREIGN KEY (idclient) REFERENCES clients(idclient) ON DELETE CASCADE);
然后,要删除所有对公司的引用,只需运行
DELETE FROM company WHERE idcompany = (insert company id variable here);
您可以查看有效的sql演示here。
如果您需要更改约束以包含DELETE CASCADE
,请查看this post。