从两个表的并集得出结果

问题描述 投票:0回答:1

分页两个大表时遇到问题:

Receipts table: id, receipt_date, record_details (650k records)
Z Reports table: id, receipt_date, record_details (88k records)

我想要做的是通过receipt_date和union对这两个表进行排序,之后我想对它们进行分页。目前我有这个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
1个回答
0
投票

有一种叫做Seek Method的技术,你可以阅读有关here的内容。根据它,您需要标识一组唯一标识每一行的列。在搜索数据库时,这组列将与谓词一起使用。

我提到的链接有一些例子,但这是另一个例子,一个非常简单的例子:

CREATE TABLE IF NOT EXISTS `docs` (
  `id` int(6) unsigned NOT NULL,
  `rev` int(3) unsigned NOT NULL,
  `content` varchar(200) NOT NULL,
  PRIMARY KEY (`id`,`rev`)
) DEFAULT CHARSET=utf8;
INSERT INTO `docs` (`id`, `rev`, `content`) VALUES
  ('1', '1', 'The earth is flat'),
  ('2', '1', 'One hundred angels can dance on the head of a pin'),
  ('1', '2', 'The earth is flat and rests on a bull\'s horn'),
  ('1', '3', 'The earth is like a ball.');

SELECT *
FROM `docs`
ORDER BY rev, id
LIMIT 2;


SELECT * 
FROM `docs`
WHERE (rev, id) > (1, 2) # let's use the last row from the previous select with the predicate
ORDER BY rev, id
LIMIT 2;

SELECT * 
FROM `docs`
WHERE (rev, id) > (3, 1) # same idea
ORDER BY rev, id
LIMIT 2;

SQLFiddle Link

拥有索引将进一步加快分页。

我希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.