2012-12-05 104 views
2

我正在从数据库中删除,但不是连接表的工作删除,我选择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

您是否有现有的SELECT查询可以向我们展示不基于我们的某个查询。什么能够显示你过去如何加入你所有的餐桌? – Andrew

+0

我还没有加入任何表格。当我做选择时,我只编辑了一个表 – Meredith

回答

3

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

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

因为我并不确切地知道你的表是如何组织的,你就必须纠正联接语法来匹配你通常如何加入他们的行列。为获得进一步的帮助,请尝试编辑您的问题,并为我们提供2个表中的所有字段名称。

+0

。它现在包括我所有的表和什么是在每个表 – Meredith

0

试试这个::

DELETE from costumes where costumeid in 
(
Select temp_costume.id from 
(Select costume_id as id from table.... 
) as temp_costume 
+0

安德鲁答案会更好imho –

1

我认为你应该使用外键的ON DELETE CASCADE属性。使用这个,当你删除一件服装时,它会删除历史表中的那个客户。

+1

好点。如果正确设置了“外键约束”,当从主表中删除一行时,其他表中的相关行将被删除:http://dev.mysql.com/doc/refman/5.5/en/innodb - 对外商琴键constraints.html – Andrew