2012-12-05 99 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