我学习了基于页面的分页和光标分页。在这两个方面,我都需要总计数来显示更多结果或不显示更多结果。问题是我计算每个新页面的所有行。这很糟糕,那么有没有一个解决方案可以让我绕过它或以高性能的方式实现它?
SELECT
wp.id,
u.id as user_id, u.firstname, u.lastname,
c.id as company_id, c.company,
wst.id as wst_id,
wst.start_time,
wst.end_time,
wst.send_start_at,
wst.send_end_at,
l.name as location,
(
SELECT
COUNT(wp.id) as total
FROM workers_plan wp
LEFT JOIN users u
ON u.id = wp.user_id
WHERE wp.tenant_id = $1 AND wst.deleted_by IS NULL AND ($3 OR u.company_id = $2)
) AS total
FROM workers_plan wp
LEFT JOIN users u ON u.id = wp.user_id
LEFT JOIN clients c ON c.id = u.company_id
LEFT JOIN workers_plan wp ON wst.workers_plan_id = wp.id
LEFT JOIN location_orders lo ON lo.id = wp.location_orders_id
LEFT JOIN location l ON l.id = lo.location_id
WHERE wst.tenant_id = $1 AND wst.deleted_by IS NULL AND ($3 OR u.company_id = $2)
GROUP BY wp.id, wst.id, u.id, c.id, l.name
ORDER BY wp.id, wp.created_at LIMIT 50
在这里您可以看到我有一个子查询,我在其中计算所有行(总计)。每 50 个结果后执行一次。
除了查询不进行任何分页之外,不需要总计数来知道是否有更多结果。
limit
结果,则没有更多结果。limit
结果,您仍然可以显示“加载更多”,最终会出现在空白页面上。这取决于您是否可以接受。limit + 1
结果并仅显示最多 limit
。如果最后一个结果存在(在您的示例中为第 51 个),您就知道还有更多结果。