2012-11-20 16 views
0

我有一個功能,我不喜歡,功能從表中刪除產品。將多個刪除查詢組合成更少?

這也會刪除該產品的所有類別,標籤和變體, ,並且對於每個變體刪除其所有圖像,文檔和值。

這歸結爲兩個選擇查詢和六個刪除查詢。

有沒有辦法讓這個數據庫密集程度降低?

delete from $this->table where id = $id 
delete from $this->clink where product_id = $id 
delete from $this->tlink where product_id = $id 

$variants = select id from $this->vlink where product_id = $id //e.g. (1,2) 

delete from $this->vlink where product_id = $id 
delete from cart_variant_values where variant_id in $variants 
delete from cart_variant_images where variant_id in $variants 
delete from cart_variant_documents where variant_id in $variants 

我希望我可以做這樣的事情:

variants = select id from $this->vlink where product_id = $id //e.g. (1,2) 

delete from $this->table where id = $id 
delete from $this->clink, $this->tlink, $this->vlink where product_id = $id 
delete from cart_variant_values, cart_variant_images, cart_variant_documents 
where variant_id in $variants 

但顯然還是不行!


編輯(2012年11月21日):

將這項工作?

DELETE vi, vv, vd, v, p, pc, pt 
FROM cart_variant_images vi 
INNER JOIN cart_variant_values vv 
INNER JOIN cart_variant_documents vd 
INNER JOIN cart_product_variants v ON vd.variant_id = v.id 
INNER JOIN cart_products p ON v.product_id = p.id 
INNER JOIN cart_products_categories pc ON p.id = pc.product_id 
INNER JOIN cart_products_tags pt ON p.id = pt.product_id 
WHERE p.id = $id; 

該查詢拋出我沒有錯誤,但我想知道它是否會做我想要的?

請注意,每個表中將有不同數量的行,那麼內部連接是否正確連接?

+0

多表刪除語法:http: //dev.mysql.com/doc/refman/5.5/en/delete.html –

回答

3

使用外鍵與ON DELETE CASCADE

+0

@Hailwood或加入,如果你有MyISAM – nkamm