[英]Codeigniter: MySQL query - Distinct + Count
我需要幫助使此查詢輸出我想要的東西。 我試圖使用與眾不同並一起計算,但我不知道如何。 以下是我的order_item表和當前使用的代碼。
order_id | product_carrier_link | Product_condition
------------------------------------------------
5001 89 1
5001 89 2
5001 89 1
5001 89 1
5001 89 1
5001 89 2
5001 89 2
$this->db->select('*');
$this->db->from('order_item');
$this->db->where('order_id', $id);
$this->db->group_by('product_carrier_link');
$this->db->group_by('product_condition');
$this->db->distinct('product_condition');
$query = $this->db->get();
return $query->result();
這導致以下
order product condition
5001 89 1
5001 89 2
我需要計算具有product_condition 1和product_condition 2的行。我希望它們以數量顯示。 例如:
order product condition qty
5001 89 1 4
5001 89 2 3
任何幫助,將不勝感激。
在手冊中 ,DISTINCT通常被視為GROUP BY的特例:
例如,以下兩個查詢是等效的:
SELECT DISTINCT c1, c2, c3 FROM t1 WHERE c1 > const; SELECT c1, c2, c3 FROM t1 WHERE c1 > const GROUP BY c1, c2, c3;
在您的情況下,您將獲得所需的輸出,如下所示(您無需使用DISTINCT):
$this->db->select('*, count( condition ) AS qty');
$this->db->from('order_item');
$this->db->where('order_id', $id);
$this->db->group_by('product_carrier_link');
$this->db->group_by('product_condition');
$query = $this->db->get();
return $query->result();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.