2012-06-05 59 views
1

這是可能集中在以最好的方式工作,如果有其他選擇問題或者說是唯一的出路:返回查詢和行的單一功能的總數的結果

使用Codeigniter ...我有列表記錄的典型2個功能,並顯示記錄總數(使用頁面作爲替代)。問題在於它們相當大。樣本2層的功能在我的模型:

數行:每頁

function get_all_count() 
    { 
     $this->db->select('u.id_user'); 
     $this->db->from('user u'); 
     if($this->session->userdata('detail') != '1') 
     { 
      $this->db->join('management m', 'm.id_user = u.id_user', 'inner'); 
      $this->db->where('id_detail', $this->session->userdata('detail')); 
      if($this->session->userdata('management') === '1') 
      { 
       $this->db->or_where('detail', 1); 
      } 
      else 
      { 
       $this->db->where("id_profile IN (
           SELECT 
           e2.id_profile 
           FROM profile e, profile e2, profile_path p, profile_path p2 
           WHERE e.id_profile = " . $this->session->userdata('profile') . " 
           AND p2.id_profile = e.id_profile 
           AND p.path LIKE(CONCAT(p2.path,'%')) 
           AND e2.id_profile = p.id_profile 
           )", NULL, FALSE); 

       $this->db->where('MD5(u.id_user) <>', $this->session->userdata('id_user')); 
      } 
     }  
     $this->db->where('u.id_user <>', 1); 
     $this->db->where('flag <>', 3); 
     $query = $this->db->get(); 
     return $query->num_rows(); 
    } 

結果

function get_all($limit, $offset, $sort = '') 
    { 
     $this->db->select('u.id_user, user, email, flag'); 
     $this->db->from('user u'); 
     if($this->session->userdata('detail') != '1') 
     { 
      $this->db->join('management m', 'm.id_user = u.id_user', 'inner'); 
      $this->db->where('id_detail', $this->session->userdata('detail')); 
      if($this->session->userdata('management') === '1') 
      { 
       $this->db->or_where('detail', 1); 
      } 
      else 
      { 
       $this->db->where("id_profile IN (
           SELECT 
           e2.id_profile 
           FROM profile e, profile e2, profile_path p, profile_path p2 
           WHERE e.id_profile = " . $this->session->userdata('profile') . " 
           AND p2.id_profile = e.id_profile 
           AND p.path LIKE(CONCAT(p2.path,'%')) 
           AND e2.id_profile = p.id_profile 
           )", NULL, FALSE); 

       $this->db->where('MD5(u.id_user) <>', $this->session->userdata('id_user')); 
      } 
     } 
     $this->db->where('u.id_user <>', 1); 
     $this->db->where('flag <>', 3); 
     if($sort) $this->db->order_by($sort); 
     $this->db->limit($limit, $offset); 
     $query = $this->db->get(); 
     return $query->result();  
    } 

你看,我重複最多的功能,不同的是,只有字段和管理頁面的數量。

我不知道是否有任何替代方法可以在單個函數中獲得與查詢一樣多的結果。我見過很多教程,並且都創建了2個功能:一個用於計數,另一個用於顯示結果...是否會有更優化?

+0

我猜使用'SELECT COUNT(* )FROM ...'不是一個選項? – FrustratedWithFormsDesigner

+0

類似SQL_CALC_FOUND_ROWS – csotelo

回答

0

你在查詢中使用SQL_CALC_FOUND_ROWS,像這樣:

SELECT SQL_CALC_FOUND_ROWS first_name, age FROM table 

返回,你可以簡單地創建一個新的數組結果:

$result['total'] = $this->db->query("SELECT FOUND_ROWS() as total")->row_array(); 
$result['result_array'] = $query->result(); 
return $result;