Reputation: 7618
I have a script that makes a union
with different tables of my database.
I need to show the result with pagination to make it more readable to the user.
This is my code:
//Fetch
foreach($query_info->result() as $info){
//I'm going to create a query for each row i get from the db
$query [] = (' (
SELECT
'.$info->slug.'_dog.`name`,
`age`,
'.$info->slug.'_breed.`name` as breed,
`sex`,
`link`,
`sterilized`,
\''.$info->slug.'\' as prefix
FROM
'.$info->slug.'_dog,
'.$info->slug.'_breed
WHERE
'.$info->slug.'_dog.breed = '.$info->slug.'_breed.id
AND
'.$info->slug.'_dog.type = '.$type.'
)';
}
//implode different UNION
$query_final = implode(" UNION ",$query);
As you can see the the query could be very big. How can I paginate?
My second option is make a full View with all the result of the tables, about 10-20 tables... Which is faster for the database? the "big" UNION or a View?
Upvotes: 1
Views: 1060
Reputation: 3240
I don't know which is faster, but to do the UNION, you can add an offset and limit to the end of the total query for your pagination. In only the first query, you can add SQL_CALC_FOUND_ROWS in the select. Something like this: (Note that there is no comma after SQL_CALC_FOUND_ROWS)
(SELECT SQL_CALC_FOUND_ROWS column1, column2 FROM etc...) UNION (SELECT column1, column2 FROM etc...) LIMIT 0,10
After you have ran the query, immediately run this query:
SELECT FOUND_ROWS();
It will return the total records like there was no LIMIT on your query. So basically you do not have to run the query again to count the results.
For creating the rest of the pagination, you can use CI it's own pagination library: http://codeigniter.com/user_guide/libraries/pagination.html
// Edit: For returning data from the model, you could use something like this:
$results['data'] = $this->db->query($sql)->result_array();
$total = $this->db->query('SELECT FOUND_ROWS() as total')->row_array();
$results['total'] = $total['total'];
return $results;
It can probably be optimized a bit more.
Upvotes: 2