2

我正在从数据库中删除,而不是加入表,我选择了服装 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'");

该查询给了我约束问题

4

3 回答 3

3

您应该在删除语句中加入您的表。所以完成这个查询然后尝试一下:

DELETE costumes, history
FROM costumes JOIN history ON costume.costume_id = history.costume_id
WHERE costume_id = '$db_id';

由于我不确切知道您的表的结构,您必须更正连接语法以匹配您通常连接它们的方式。如需进一步帮助,请尝试编辑您的问题并将您的 2 个表格中的所有字段名称提供给我们。

于 2012-12-05T07:38:05.640 回答
1

我认为您应该使用ON DELETE CASCADE外键的属性。使用它,当您删除服装时,它也会从历史表中删除该客户。

于 2012-12-05T08:03:05.967 回答
0

尝试这个::

DELETE from costumes where costumeid in 
(
Select temp_costume.id from
( Select costume_id as id from table....
) as temp_costume
于 2012-12-05T07:39:12.837 回答