2015-09-23 128 views
0

這是我笨查詢MySQL查詢優化和更新需要

$this->db->select('o.*,seo.price as seo_price,SUM(domain.price) as domain_price,SUM(bes.price) as bes_price, SUM(op.price) as payment_price'); 
    $this->db->from('order as o'); 
    $this->db->join("order_package_seo as seo", "seo.order_id = o.id", "left"); 
    $this->db->join("order_package_domain as domain", "domain.order_id = o.id", "left"); 
    $this->db->join("order_package_bespoke as bes", "bes.order_id = o.id", "left"); 
    $this->db->join("order_payment as op", "op.order_id = o.id", "left"); 
    $this->db->where("o.id" , $id); 
    $query = $this->db->get(); 
    return $query->row(); 

我有3條在「order_package_beskope」表和其他1所有 我想擺脫所有的表價格ORDER_ID 被我需要使用group_by獨特或任何其他方法需要你的建議。

+0

確定,所以什麼是它返回.. –

+1

它返回所有的價格多由3添加組。即域名價格是123,但其返回369. –

+1

我可以解釋更多,如果你可以幫助.. –

回答

0

變化這樣

$this->db->select('o.*,seo.price as seo_price,domain.price ,SUM(bes.price) as bes_price, op.price as payment_price'); 
$this->db->from('order as o'); 
$this->db->join("order_package_seo as seo", "seo.order_id = o.id", "left"); 
$this->db->join("order_package_domain as domain", "domain.order_id = o.id", "left"); 
$this->db->join("order_package_bespoke as bes", "bes.order_id = o.id", "left"); 
$this->db->join("order_payment as op", "op.order_id = o.id", "left"); 
$this->db->where("o.id" , $id); 
$this->db->group_by("o.id"); 
$query = $this->db->get(); 
return $query->row(); 

第一個語句,因爲,你提到的表「order_package_beskope」有3條記錄,因此只有表的字段「bes_price」需要的總和。所有其他表只有一條記錄,因此如果添加SUM,它將乘以3(order_package_bespoke記錄的數量)。

所以在選擇其他表中的字段刪除SUM和o.id