$this->db->group_by()并添加数量


$this->db->group_by() and adding the quantity

我在我的收据UI中有这个(注意:这只是来自一个用户):

    Item_Name | Quantity | Price | Total
     Panty    |     2    |  50   |  100
      Bra     |     1    |  35   |   35
     Panty    |     2    |  50   |  100

正如你所看到的,用户得到了内裤两次!

我想让我的UI看起来像这样:

    Item_Name | Quantity | Price | Total
     Panty    |     4    |  50   |  100
      Bra     |     1    |  35   |   35

你可以看到用户购买的Panty's组合在一起,但在我的查询中,Panty的数量不是4个,而是2个

下面是我的代码:

public function getClientReservation($name){
    $this->db->select('*');
    $this->db->from('tbl_item_availed');
    $this->db->join('tbl_items','tbl_items.Item_ID = tbl_item_availed.Item_ID');
    $this->db->join('user_account','user_account.Account_no = tbl_item_availed.Account_no');
    $this->db->where('Username',$name);
    $this->db->where('isReserve',1);
    $this->db->where('Active',1);
    $this->db->group_by('tbl_items.Item_Name');
    $query = $this->db->get();
    return $query->result();
} 

请帮忙!

表tbl_item_availed:

   Item_availed_id | Item_ID | Quantity | Account_no
        1          |    1    |    2     |    5
        2          |    2    |    1     |    5
        3          |    1    |    2     |    5
表tbl_items:

   Item_ID | Price | Item_Name
       1   |  100  |  Panty
       2   |  35   |   Bra
表user_account:

   Account_no | Firstname | Lastname
       1      |  LeBron   |  James
       2      |  Dwyane   |   Wade
       3      |   Wilt    |  Chamberlain
       4      | Michael   |  Jordan
       5      | Charles   |  Barkley

试试这个

public function getClientReservation($name){
    $this->db->select('tbl_items.`Item_Name`, SUM(tbl_item_availed.`Quantity`) AS quantity, tbl_items.`Price`, (tbl_items.`Price`*(SUM(tbl_item_availed.`Quantity`))) AS total');
    $this->db->from('tbl_item_availed');
    $this->db->join('tbl_items','tbl_items.Item_ID = tbl_item_availed.Item_ID');
    $this->db->join('user_account','user_account.Account_no = tbl_item_availed.Account_no');
    $this->db->where('Username',$name);
    $this->db->where('isReserve',1);
    $this->db->where('Active',1);
    //$this->db->group_by('tbl_items.Item_Name');//do not use this line unless item name is unique
    //group by item id
    $this->db->group_by('tbl_items.Item_ID');

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

对于Item_ID也使用GROUP BY(假设它是唯一的),而不是Item_Name,除非它是唯一的。

边注:

WHERE子句中,用Account_no代替username。如果您想修改它,只需替换这一行

$this->db->where('Username',$name);

$this->db->where('Account_no',$account_no);