簡體   English   中英

codeigniter活動記錄獲取沒有LIMIT子句的查詢和查詢

[英]codeigniter active record get query and query without the LIMIT clause

即時通訊使用活動記錄,它的工作正常,但我想將$ data [“totalres”]設置為總結果,我的意思是相同的查詢,但沒有LIMIT

問題是當你執行查詢修飾符時,前面的語句被取消設置,所以我甚至不能在得到結果后添加$ this-> db-> limit()。

有任何想法嗎? 我認為,為了做到這一點,“復制”查詢是一種不好的做法

function get_search($start, $numrows, $filter = array())
{    

    ...

    $this->db
    ->select("emp")
    ->from('emp')
    ->join('empr', 'empr.b = empr.id', 'left')
    ->like('code', $code)
    ->limit($numrows, $start);

    ...

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

    // number of rows WITHOUT the LIMIT X,Y filter
    $data["totalres"] = ???????;        

    if ($q->num_rows() > 0)
    {        
        $data["results"] = $q->result();
    } else {
        $data["results"] = array();
    }   

    return $data;
}    

您可以使用SQL_CALC_FOUND_ROWS來獲取將返回的行數SQL_CALC_FOUND_ROWS - LIMIT 注意select行中的,FALSE 這告訴CodeIgniter不要嘗試使用反引號來轉義SELECT子句(因為SQL_CALC_FOUND_ROWS不是字段,而CodeIgniter沒有意識到這一點)。

$this->db
->select("SQL_CALC_FOUND_ROWS emp", FALSE)
->from('emp')
->join('empr', 'empr.b = empr.id', 'left')
->like('code', $code)
->limit($numrows, $start);

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

然后在運行該查詢之后,我們需要運行另一個查詢來獲取總行數。

$query = $this->db->query('SELECT FOUND_ROWS() AS `Count`');
$data["totalres"] = $query->row()->Count;

我實際上建議使用CI查詢緩存。

要使用它,您可以啟動緩存,在沒有限制的情況下構建查詢。 運行查詢以獲取完整計數,然后應用限制並運行查詢以獲取具有所需偏移量的頁面列表。

緩存將記住已定義的變量。

然后,您可以清除緩存以進行后續查詢。

    $this->db->start_cache();

    // Where, like, having clauses in here

    $this->db->stop_cache();

    $count = $this->db->get('table')->num_rows();

    $this->db->limit('limit', 'offset');

    $result = $this->db->get('table')->result_array();

    $this->db->flush_cache();

試試這個:

function get_search($start, $numrows, $filter = array()){    
    $tmp= $this->db
    ->select("emp")
    ->from('emp')
    ->join('empr', 'empr.b = empr.id', 'left')
    ->like('code', $code)
    ->_compile_select();

    $q= $this->db->limit($numrows, $start)->get();

    // number of rows WITHOUT the LIMIT X,Y filter

    $data["totalres"] = $this->db->query($tmp)->num_rows();

    if ($q->num_rows() > 0){        
        $data["results"] = $q->result();
    } else {
        $data["results"] = array();
    }   
    return $data;
}    
$this->db
->select("SQL_CALC_FOUND_ROWS emp", FALSE)
->from('emp')
->join('empr', 'empr.b = empr.id', 'left')
->like('code', $code)
->limit($numrows, $start); $q = $this->db->get();

$query = $this->db->query('SELECT FOUND_ROWS() AS `Count`');
$data["totalres"] = $this->db->get()->row()->Count;

CodeIgniter 2.1.0沒有運行,下面的代碼會修復它。

$query = $this->db->query('SELECT FOUND_ROWS() AS `Count`');
$objCount = $query->result_array();
$data["totalres"] = $objCount[0]['Count'];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM