1

我需要在使用 LIMIT 的 UNION ALL SELECT 查询中获取单个 SELECT 语句的行数。MySQL 文档非常清楚获取查询的全局行数(将单个 SELECT 放在括号中,并仅在第一条语句中放置 SQL_CALC_FOUND_ROWS,然后以通常的方式获取 FOUND_ROWS())。但是,我还需要单个SELECT 语句的结果行数。查询,简化:

(SELECT SQL_CALC_FOUND_ROWS `field1`,`field2` FROM `db`.`table1` WHERE `id`>1000)
UNION ALL
(SELECT `field1`,`field2` FROM `db`.`table2` WHERE `id`>1000)
UNION ALL
...
(SELECT `field1`,`field2` FROM `db`.`tableN` WHERE `id`>1000)
LIMIT 0,10

如果在每个SELECT 语句中放置 SQL_CALC_FOUND_ROWS,则会发出“'SQL_CALC_FOUND_ROWS' 的使用/放置不正确”错误。谷歌了很多,在这里阅读相关消息,无济于事。可能是非常简单的事情,我只是无法理解它。

4

1 回答 1

0

您收到该错误是因为 SQL_CALC_FOUND_ROWS 可用于查询以将单个数字返回到 FOUND_ROWS()。

您可以通过以下方式返回计数:

SELECT 'table1' AS tablename, COUNT(1) AS rowcount FROM table1 WHERE id > 1
UNION ALL
SELECT 'table2' AS tablename, COUNT(1) AS rowcount FROM table2 WHERE id > 1
...
SELECT 'tableN' AS tablename, COUNT(1) AS rowcount FROM tableN WHERE id > 1

如果这有帮助。

如果要从表中返回带有计数的行,请修改它:

SELECT field1, field2, (SELECT COUNT(1) FROM table1 WHERE id > 1000) FROM table1 WHERE id > 1000
UNION ALL
SELECT field1, field2, (SELECT COUNT(1) FROM table2 WHERE id > 1000) FROM table2 WHERE id > 1000
...
SELECT field1, field2, (SELECT COUNT(1) FROM tableN WHERE id > 1000) FROM tableN WHERE id > 1000

从你的问题来看,你想要达到的目标并不完全清楚。

于 2009-08-23T10:29:43.283 回答