簡體   English   中英

在帶有 ORDER BY 和 LIMIT 的代碼點火器中使用 UNION ALL 會出錯

[英]Using UNION ALL in code igniter with ORDER BY and LIMIT gives error

我必須將包含兩種類型的帖子的兩個不同的表合並到一個包含所有帖子的表中。 我試過使用 UNION ALL 並且我得到了很好的結果,直到我必須添加分頁。

  $this->db->select("id,article_type,title,main_img1,open_date");
        $this->db->from('table1');
        $query1 = $this->db->get_compiled_select();
        $this->db->reset_query();
        
       $this->db->select("id,article_type,title,main_img1,open_date");
        $this->db->from('table2');
        $query2 = $this->db->get_compiled_select();
        $this->db->reset_query();
            
        $articles = $this->db->query($query1 . ' UNION ALL ' . $query2);
     
        $data['total_rows'] = $articles->num_rows();
        
        /*pagination*/
        $page = $this->input->get('page') ? $this->input->get('page') : 1;
        $this->load->library("pagination");
        $this->config->load('pagination', true);
        $config = $this->config->item('pagination');
        $config['reuse_query_string'] = TRUE;
        $config['query_string_segment'] = 'page';
        $config["base_url"] = site_url('example/index');
        $config["total_rows"] = $data['total_rows'];
        $config["per_page"] = 9;
        $config["offset"] = ($page - 1) * $config["per_page"];
        $this->pagination->initialize($config);
        $data['column_pagination'] = $this->pagination->create_links();
        
        /* get records */
         $query = $this->db->query($articles . 'ORDER BY open_date DESC, id DESC LIMIT ' . $config["offset"] . ',' . $config["per_page"]);
        $data['article_posts'] = $query->result_array();

我正在使用現有的代碼,似乎統一表不能很好地使用 ORDER BY 和 LIMIT。 有人有解決辦法嗎??

更新:我的原始代碼有一個 query2。 抱歉錯字。

您使用了錯誤的變量,請更改

 $query = $this->db->query($articles . 'ORDER BY open_date DESC, id DESC LIMIT ' . $config["offset"] . ',' . $config["per_page"]);

 $query = $this->db->query($query1 . ' UNION ALL ' . $query2 . ' ORDER BY open_date DESC, id DESC LIMIT ' . $config["offset"] . ',' . $config["per_page"]);

因為 Articles 不是字符串,它是數據庫 object。 您還需要在 ORDER BY 之前有一個空格,因為原始查詢不包含該空格。

如果你真的想要動態

 $query = $this->db->query($this->db->last_query() . ' ORDER BY open_date DESC, id DESC LIMIT ' . $config["offset"] . ',' . $config["per_page"]);

順便說一句,您知道您沒有 $query2 嗎?

暫無
暫無

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

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