【问题标题】:Codeigniter: Summary from two tablesCodeigniter:来自两个表的摘要
【发布时间】:2013-02-19 04:51:39
【问题描述】:

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

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();

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

【问题讨论】:

标签: php mysql codeigniter activerecord


【解决方案1】:

试试这个:

$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 fiddle 演示在这里: http://sqlfiddle.com/#!2/04164/2

【讨论】:

  • 这正是我要找的!非常感谢您以活动记录格式编写它。
【解决方案2】:

即使事务表中的第三个产品没有关系,您也需要使用完全连接来获取两个表的摘要......

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

【讨论】:

  • 您好,您的查询只显示产品书和笔。标尺不显示。在我的项目中,table_product 上实际上有 12 个项目。我想把它们都展示出来,即使总数是 0。
猜你喜欢
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-31
  • 2022-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多