2013-10-08 43 views
1

的嘗試代碼排序:笨活動記錄 - 防止重複,按日期

$this->db->select('*'); 
    $this->db->from('documents_table'); 
    $this->db->order_by("last_modified_date", "desc"); 
    $this->db->group_by('document_id'); 

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

表結構:

ID,DOCUMENT_ID,內容,LAST_MODIFIED_DATE

問題:

設計系統意味着更新文檔時,將使用相同的document_id和更新的內容創建實際的新記錄。

現在我需要將文檔顯示在列表中,但是如果它們是具有相同document_id的多個文檔(基本上是舊版本的文件),則只應顯示最新版本。當前代碼只輸出第一個版本,所以需要切換。

是group_by正確的方法嗎?任何有經驗的人都可以弄清楚爲什麼它不按預期工作,還是我做錯了?

回答

1
$this->db->select('*'); 
$this->db->from('documents_table'); 
$this->db->order_by("last_modified_date", "desc");  
$this->db->where('id IN (SELECT MAX(id) FROM documents_table GROUP BY document_id)'); 

試一試(未經測試)。

+0

完美!根據需要工作!非常感激! –

0
$this->db->select('MAX(id) , document_id , content , last_modified_date'); 
$this->db->from('documents_table'); 
$this->db->order_by("last_modified_date", "desc"); 
$this->db->group_by('document_id'); 

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

未經測試

+0

沒有。仍然得到舊的記錄,而不是最新的記錄。 –