我对一个函数不满意,该函数从表中删除了一个产品。
这还会删除该产品的所有类别、标签和变体, 并针对每个变体删除其所有图像、文档和值。
这归结为两个选择查询和六个删除查询。
有什么方法可以减少数据库密集度吗?
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;
该查询没有向我抛出任何错误,但我想知道它是否会执行我想要的操作?
请注意,每个表中的行数会有所不同,那么 inner join 是右连接吗?
最佳答案
在 ON DELETE CASCADE
中使用外键
关于mysql - 将多个删除查询组合成更少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13471895/