我不知道 MySql 但对于许多 dbs,我想你会发现运行它两次的成本并不像你想象的那么高 - 如果你这样做的方式是 db 的优化引擎看到两个查询有很多共同点。
跑步
select count(1) from (
select some_fields, row_number over (order by field) as rownum
from some_table
)
接着
select * from (
select some_fields, row_number over (order by field) as rownum
from some_table
)
where rownum between :startRow and :endRow
order by row_number
这还有一个好处是您可以只在一个地方使用两个不同的包装器来维护查询,1 个用于分页,1 个用于获取总计数。
顺便说一句,您可以做的最佳优化是确保每次都向数据库发送完全相同的查询。换句话说,如果用户可以更改排序或更改他们可以查询的字段,那么将它们全部烘焙到同一个查询中。例如:
select some_fields,
case
when :sortField = 'ID' and :sortType = 'asc'
then row_number over (order by id)
when :sortField = 'ID' and :sortType = 'desc'
then row_number over (order by id desc)
end as rownum
from some_table
where (:searchType = 'name'
and last_name like :lastName and first_name like :firstName)
or (:searchType = 'customerType'
and customer_type = :customer_type)