Codeigniter:两个表的摘要

时间:2013-02-19 04:51:40

标签: php mysql codeigniter activerecord

我需要使用以下格式打印两个表中的摘要:

Product | Grand Total
--------+---------
 Book   | 8000
 Pen    | 5000
 Ruler  | 0

table_product

 id  | name
-----+---------
 1   | Book
 2   | Pen
 3   | Ruler

table_transaction

 id  | cashier | product | total
-----+---------+---------+---------
 1   | john    |    1    | 5000
 2   | doe     |    1    | 3000
 3   | john    |    2    | 2000
 4   | other   |    2    | 3000

这只能用1个查询来完成吗?

修改 之前,我在table_transaction上使用了这个查询:

$this->db->select('product');
$this->db->select('total');
$this->db->from('table_transaction');
$this->db->select_sum('total', 'grand_total');
$this->db->group_by('product'); 
$query = $this->db->get();

但它还没有显示表中没有的产品。 我想打印所有产品,即使还没有交易。

2 个答案:

答案 0 :(得分:0)

您需要使用Full join来获取两个表的摘要,即使事务表中第三个产品没有关系....

select product.name,transaction.total from product left join transaction on product.p_id = transaction.p_id

答案 1 :(得分:0)

试试这个:

$this->db->select('t1.name, sum(t2.total) as grand_total');
$this->db->from('table_product t1');
$this->db->join('table_transaction t2', 't2.product = t1.id', 'left');
$this->db->group_by('t1.name');
$query = $this->db->get();

sql小提琴演示在这里: http://sqlfiddle.com/#!2/04164/2