我正在努力从数据库中删除但不是加入表,我选择了costume_id(主键)并尝试删除这种方式,但它似乎只从一个表而不是所有表中删除。我已经尝试在主键之前删除外键但这不起作用。我是否必须加入表格然后删除或以我的方式工作?
$select = $mysqli->query("SELECT * FROM costumes WHERE $q");
while ($row = $select->fetch_assoc())
$db_id = $row["costume_id"];
$costume = $mysqli->query("DELETE FROM costumes WHERE costume_id='$db_id'");
$costume_row = $costume->fetch_assoc();
$history = $mysqli->query("DELETE FROM history WHERE history_id='$db_id'");
$history_row = $history->fetch_assoc();
$location = $mysqli->query("DELETE FROM location WHERE location_id='$db_id'");
$location_row = $location->fetch_assoc();
$state = $mysqli->query("DELETE FROM state WHERE state_id='$db_id'");
$state_row = $state->fetch_assoc();
$ q是一个子流。在我的表中有:
costumes (
costume_id varchar(10) primary key,
name varchar(50),
is_seperate bool,
is_onepeice bool,
description text,
color varchar(25),
material varchar(50),
genre varchar(25),
gender char(1),
size varchar(5)
);
state (
state_id varchar(10),
in_use bool,
fixed bool,
condition text,
foreign key (state_id) references costume(costume_id)
);
history (
history_id varchar(10),
previous_user varchar(20),
profession varchar(20),
previous_play varchar(50),
date date, fixed_previous bool,
comments text,
foreign key (history_id) references costume (costume_id)
);
location (
location_id varchar(10),
loc_no varchar(10) primary key,
room_no varchar(3),
foreign key (location_id) references costumes (costume_id)
);
我的删除新查询是:
$delete = $mysqli->query("DELETE costumes,history,status,location FROM costumes join history on costumes.costume_id = history.history_id join status on status.status_id join location on location.location_id where costume_id='$db_id'");
该查询给了我约束问题
答案 0 :(得分:3)
您应该在delete语句中加入表。所以完成此查询然后尝试:
DELETE costumes, history
FROM costumes JOIN history ON costume.costume_id = history.costume_id
WHERE costume_id = '$db_id';
由于我不确切知道您的表的结构,因此您必须更正连接语法以匹配您通常加入它们的方式。如需进一步的帮助,请尝试编辑您的问题,并在2个表格中为我们提供所有字段名称。
答案 1 :(得分:1)
我认为你应该使用外键的ON DELETE CASCADE
属性。使用此功能,当您删除服装时,它也会删除历史记录表中的该客户。
答案 2 :(得分:0)
试试这个::
DELETE from costumes where costumeid in
(
Select temp_costume.id from
( Select costume_id as id from table....
) as temp_costume