将多个删除查询修改为尽可能少的更新查询?

时间:2012-11-27 10:48:28

标签: php mysql codeigniter query-optimization

我们目前有这段代码:

$this->db->where('id', $id)->delete($this->table);
$this->db->where('product_id', $id)->delete($this->clink);
$this->db->where('product_id', $id)->delete($this->tlink);

$variants = $this->db->select('id')->from($this->vlink)->where('product_id', $id)->get();
if ($variants->num_rows() !== 0) {

    //turns array(array('id' => 1), array('id' => 2)) into array(1,2)
    $variants = $variants->result_array();
    foreach ($variants as &$v) {
        $v = $v['id'];
    }

    $this->db->where('product_id', $id)->delete($this->vlink);
    $this->db->where_in('variant_id', $variants)->delete('cart_variant_values');
    $this->db->where_in('variant_id', $variants)->delete('cart_variant_images');
    $this->db->where_in('variant_id', $variants)->delete('cart_variant_documents');
}

这转化为:

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

现在我需要修改代码,而不是删除所有行,而是在它们上设置end_date列。

我知道我可以修改它。留下相同数量的查询,但我希望更新而不是删除我可以将其缩小为更少的查询?

1 个答案:

答案 0 :(得分:0)

如果您担心删除查询的数量,可以使用多表删除查询,通过该查询可以将其缩减为单个查询
DELETE Syntax

您也可以在UPDATE中实施多个表格查询 UPDATE Syntax