2016-08-16 95 views
0

我目前正在Codeigniter查詢中嘗試獲取一堆結果。但是,當我在同一個查詢中同時使用group_by和order_by時,order_by被否決並且由於某種原因而不適用。Codeigniter group_by和Order_by衝突

查詢如下:

$this->db->select('q.questionNumber, qa.qaId')->from('questions q'); 
$this->db->join('questionAnswers qa', 'qa.questionId = q.questionId'); 
$this->db->where('customerId', $customerId); 
$this->db->order_by('q.questionNumber', 'desc'); 
$this->db->group_by('q.subject'); 
$query = $this->db->get(); 
$query->result(); 

回答

1

使用更新的一個

$this->db->select('q.questionNumber, qa.qaId')->from('questions q'); 
$this->db->select_max('q.questionNumber' , 'questionNumber'); // added this 
$this->db->join('questionAnswers qa', 'qa.questionId = q.questionId'); 
$this->db->where('customerId', $customerId); 
$this->db->order_by('q.questionNumber', 'desc'); 
$this->db->group_by('q.subject'); 
$query = $this->db->get(); 
$query->result(); 
+0

@S_NoBEI它工作嗎? –

0

可以使用編寫查詢這樣的:

$query = $this->db->query("SELECT ....."); 

$query->result(); 
+1

這將如何解決這個問題? –

+0

使用基本SQL編寫您的查詢,也許一些codeigniter是如何在查詢中發生錯誤 –

0

你可以試試這個解決方案爲您查詢:

$this->db->select('q.subject,COUNT(q.questionNumber), COUNT(qa.qaId)')->from('questions q'); 
$this->db->join('questionAnswers qa', 'qa.questionId = q.questionId'); 
$this->db->where('customerId', $customerId); 
$this->db->group_by('q.subject'); 
$this->db->order_by('q.questionNumber', 'desc'); 
$query = $this->db->get(); 
$query->result(); 

需要添加查詢中選擇行的列時使用Group By Clause和具有聚合函數的其他字段。