简体   繁体   中英

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

I have to merge two different tables that contain two types of post into one table with all posts. I've tried using UNION ALL and I get good results until I have to add pagination.

  $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();

I'm using the existing code and it seems that a unified table doesn't go well with ORDER BY and LIMIT. Does anybody have a solution??

UPDATE: I have a query2 on my original code. sorry for the typo.

You used the wrong variable, change

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

To

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

Because Articles is not a String, it's a database object. You are also going to need a space before ORDER BY as the original query doesn't contain the space.

If you really want to be dynamic

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

BTW you know you don't have a $query2?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM