带有LIMIT的UNION查询(不是UNION ALL)上的SQL_CALC_FOUND_ROWS和SELECT FOUND_ROWS()

时间:2012-02-14 17:52:12

标签: php mysql

如果没有设置全局LIMIT,我正在尝试计算返回的总行数。这是我的查询的样子:

SELECT SQL_CALC_FOUND_ROWS * FROM table1 WHERE [...]
UNION
SELECT * FROM table2 WHERE [...]
UNION
SELECT * FROM table3 WHERE [...]
UNION 
SELECT * FROM table4 WHERE [...]
LIMIT 0,30

然后我立即使用SELECT FOUND_ROWS()查询。它总共返回35行,但它应返回总共400行。知道如何在不使用UNION ALL的情况下计算行数吗?

1 个答案:

答案 0 :(得分:8)

将临时表用于所有联合选择:

SELECT SQL_CALC_FOUND_ROWS * FROM 
(
  SELECT * FROM table1 WHERE [...]
  UNION
  SELECT * FROM table2 WHERE [...]
  UNION
  SELECT * FROM table3 WHERE [...]
  UNION 
  SELECT * FROM table4 WHERE [...]
)  temp_table
LIMIT 0,30