2012-05-08 68 views
0

我寫了一個查詢與codeigniters數據庫庫,它看起來像這樣,笨數據庫查詢/ MySQL的

public function getCandidateCredits($candidate_id) 
{ 
    $this->db->select('*') 
    ->from('credits') 
    ->join('candidate_has_credits', 'candidate_has_credits.credits_credit_id = credits.credit_id', 'left') 
    ->where('credits.candidates_candidate_id', (int)$candidate_id) 
    ->order_by('candidate_has_credits.date_created', 'DESC') 
    ->order_by('credits.credit_position', 'DESC'); 



    $query = $this->db->get(); 

    return $query->result_array(); 
} 

什麼這個查詢是爲了做的是,讓所有一個成員的學分,並把它們先順序按日期(最新的第一),然後按信用狀況(最高的第一)。

雖然我有一些問題,但學分應按日期排序,但只有在沒有學分的情況下,如果有學分(0 - 999),那麼在訂購學分時應該優先考慮,如果有日期和信用頭寸,那麼應該按照信用頭寸和日期對信用進行排序。

這可能嗎?我覺得我離我需要的地方很遠,我回來的結果似乎沒有明顯的順序。不知道它是否有所作爲,但date_created字段是DATETIME。

+0

當然,你只是想交換'ORDER BY'子句? – eggyal

回答

1

您正確使用左連接,但在錯誤的順序已經把ORDER BY子句,所以首先,它們翻轉:

->order_by('credits.credit_position', 'DESC') 
->order_by('candidate_has_credits.date_created', 'DESC') 

這應該做到這一點,除了現在那些沒有相應信用記錄(因此credit_position爲空)的candidate_has_credit行將最終結束,並且我假設您希望那些記錄在最前面。

有一個小竅門,推動空值使用降序排序爲您知道在這一領域獲得的最大值時,頂部:

->order_by("ifnull('credits.credit_position',1000) desc,candidate_has_credits.date_created desc") 

請注意,我用的ORDER_BY法的形式,只包含一個參數,即不應該逃避該功能,並且速度稍快。

查看ifnull documentation瞭解它是如何工作的。

0

下面是一個縮短版:

public function getCandidateCredits($candidate_id) 
{ 
    return $this->db->from('credits') 
    ->join('candidate_has_credits', 'candidate_has_credits.credits_credit_id = credits.credit_id', 'left') 
    ->where('credits.candidates_candidate_id', (int)$candidate_id) 
    ->order_by('credits.credit_position', 'DESC') 
    ->order_by('candidate_has_credits.date_created', 'DESC') 
    ->get()->result_array(); 
}