sql - How to avoid running the same expensive MySql query twice in pagination? -


assume houses table lot's of fields, related images tables, , 3 other related tables. have expensive query retrieves houses data, data related tables. need run same expensive mysql query twice in case of pagination: once current result page , once total number of records?

i'm using server-side pagination limit 0,10, , need return total number of houses along data. doesn't make sense me run same expensive query count(*) function, because i'm limiting result-set pagination. there way instruct mysql count whole query, bring current pagination data?

i hope question clear...

i don't know mysql many dbs, think you'll find cost of running twice isn't high you'd suspect - if in such way db's optimization engine sees 2 queries having lot in common.

running

select count(1) (   select some_fields, row_number on (order field) rownum   some_table ) 

and then

select * (   select some_fields, row_number on (order field) rownum   some_table ) rownum between :startrow , :endrow order row_number 

this has advantage of being able maintain query in 1 place 2 different wrappers around it, 1 paging , 1 getting total count.

just side note, best optimization can make sure send exact same query db every time. in other words, if user can change sort or change fields can query on, bake same query. e.g:

select some_fields,    case       when :sortfield = 'id' , :sorttype = 'asc'         row_number on (order id)      when :sortfield = 'id' , :sorttype = 'desc'         row_number on (order id desc)    end rownum some_table (:searchtype = 'name'    , last_name :lastname , first_name :firstname) or  (:searchtype = 'customertype'    , customer_type = :customer_type) 

Comments

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -