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;

该查询没有给我带来任何错误,但我想知道它是否会做我想要的?

请注意,每个表中会有不同数量的行,那么内连接是右连接吗?

4

2 回答 2

3

使用外键ON DELETE CASCADE

于 2012-11-20T11:09:01.680 回答
2

无论如何,最后数据库必须做同样的事情。

但是您可以通过编写一个存储过程来最小化连接,该过程在您调用一次并传递给他 $id 和 $variants 之后删除所有的东西

http://msdn.microsoft.com/en-us/library/aa174792%28v=sql.80%29.aspx

于 2012-11-20T11:12:43.623 回答