【发布时间】:2019-09-11 10:27:26
【问题描述】:
我在对两个大表进行分页时遇到问题:
Receipts table: id, receipt_date, record_details (650k records)
Z Reports table: id, receipt_date, record_details (88k records)
我想要做的是按receipt_date 和联合对这两个表进行排序,然后我想对它们进行分页。目前我有这个 SQL(不完全是,但主要思想是这个):
SELECT c.id, c.receipt_date, c.col_type FROM (
SELECT a.id, a.receipt_date, 'receipt' AS coltype
FROM `terminal_receipts` a
WHERE `a`.`deleted` IS NULL
UNION ALL
SELECT b.id, b.receipt_date, 'zreport' AS coltype
FROM z_reports` b WHERE `b`.`deleted` IS NULL
) c
ORDER BY receipt_date desc LIMIT 50 OFFSET 0
这样,服务器从两个表中选择所有记录,按日期排序,然后应用分页。
但是当行数增加时,此查询将需要更长的时间才能完成。有没有其他算法可以在不依赖表大小的情况下获得相同的结果?
【问题讨论】:
标签: mysql pagination sql-order-by union-all