2011-09-25 55 views
0

嗨,请帮我一下我对mysql/active记录很陌生(以前的所有项目都只是基本的CRUD)我想加入两张表,所以我可以生成一张我的发票表有一个小计(以竹发票数据库结构)总结加入进行中的记录

目前没有运气(语法错误)试图

$this->db->select('invoice_number, dateIssued '); 
$this->db->select('(SELECT SUM(amount * qty) FROM manage_invoice_items DISTINCT invoice_id) AS subtotal' , FALSE); 
$this->db->from('manage_invoices'); 

$this->db->join('manage_invoice_items', 'manage_invoices.id = manage_invoice_items.invoice_id'); 
$this->db->where('client_id', $client_id); 

$query = $this->db->get(); 
return $query->result(); 

$this->db->select('invoice_number, dateIssued'); 
$this->db->from('manage_invoices'); 

$this->db->join('manage_invoice_items', 'manage_invoices.id = manage_invoice_items.invoice_id'); 
$this->db->where('client_id', $client_id); 

$query = $this->db->get(); 

return $query->result(); 

我得到每个发票项目成果(我希望每张发票的结果与该发票号码的发票项目的小计相同)

希望所有的发送都像我说的那样,我对mysql不甚了解(即使引用了一个关于组合函数的好教程也很方便。

回答

2

我并不熟悉CodeIgniter/ActiveRecord,但它似乎是你想要使用GROUP BY函数对记录进行分组。我发现this link可能会有帮助。你可能想使用:

$this->db->select_sum("amount * qty"); 

$this->db->group_by("invoice_number");        
0
$this->db->select('invoice_number, dateIssued'); 
    $this->db->select('ROUND((SUM(amount * qty)), 2) AS subtotal', FALSE); 
    $this->db->from('manage_invoices'); 

    $this->db->join('manage_invoice_items', 'manage_invoices.id = manage_invoice_items.invoice_id'); 
    $this->db->where('client_id', $client_id); 
    $this->db->group_by('invoice_number'); 
    $query = $this->db->get(); 


    return $query->result(); 

感谢Narthring(我不知道group_by