CodeIgniter活动记录计数mysql记录的值

时间:2016-08-31 06:40:50

标签: php mysql codeigniter activerecord

我的活动记录查询有什么问题,SUM函数工作正常,但计数部分返回所有记录的计数。

$this->db->select(
                        '
                         t1.account_balance, 
                         t2.CustomerName AS customer,
                         t2.CustomerId,
                         SUM(IF(t3.Bargain="Sale",t3.TotalAmount,0)) AS total_sale,
                         SUM(IF(t3.Bargain="Purchase",t3.TotalAmount,0)) AS total_buy,
                         COUNT(IF(t3.Bargain="Sale",t3.Bargain,0)) AS count_sale,
                         COUNT(IF(t3.Bargain="Purchase",t3.Bargain,0)) AS count_buy,
                         '
                     ,FALSE);
    $this->db->from("balances AS t1");
    $this->db->join("customer AS t2","t2.CustomerId = t1.customer_id","left");
    $this->db->join("gold_order AS t3","t3.CustomerId = t2.CustomerId","left");
    $this->db->group_by("t3.CustomerId");
    $object = $this->db->get();

结果:

enter image description here

我想要的count_sale应该是3,count_buy应该是4:

enter image description here

2 个答案:

答案 0 :(得分:1)

试试这个

$this->db->select(
                    '
                     t1.account_balance, 
                     t2.CustomerName AS customer,
                     t2.CustomerId,
                     SUM(IF(t3.Bargain="Sale",t3.TotalAmount,0)) AS total_sale,
                     SUM(IF(t3.Bargain="Purchase",t3.TotalAmount,0)) AS total_buy,
                     SUM(IF(t3.Bargain="Sale",1,0)) AS count_sale,
                     SUM(IF(t3.Bargain="Purchase",1,0)) AS count_buy,
                     '
                 ,FALSE);
$this->db->from("balances AS t1");
$this->db->join("customer AS t2","t2.CustomerId = t1.customer_id","left");
$this->db->join("gold_order AS t3","t3.CustomerId = t2.CustomerId","left");
$this->db->group_by("t3.CustomerId");
$object = $this->db->get();

答案 1 :(得分:0)

试试这个:

$this->db->select('
                         t1.account_balance, 
                         t2.CustomerName AS customer,
                         t2.CustomerId,
                         SUM(IF(t3.Bargain="Sale",t3.TotalAmount,0)) AS total_sale,
                         SUM(IF(t3.Bargain="Purchase",t3.TotalAmount,0)) AS total_buy,
                        (SELECT count(*) from gold_order where gold_order.Bargain="Sale") AS count_sale,
                         (SELECT count(*) from gold_order where gold_order.Bargain="Purchase") AS count_buy,
                         '
                     ,FALSE);
    $this->db->from("balances AS t1");
    $this->db->join("customer AS t2","t2.CustomerId = t1.customer_id","left");
    $this->db->join("gold_order AS t3","t3.CustomerId = t2.CustomerId","left");
    $this->db->group_by("t3.CustomerId");
    $object = $this->db->get();