views:

717

answers:

1

Hi all. I need to get the row count for individual SELECT statements in an UNION ALL SELECT query that uses LIMIT. The MySQL docs are pretty clear about getting the global row count for the query (place individual SELECTs in parenthesis and place an SQL_CALC_FOUND_ROWS only in the first statement, then get FOUND_ROWS() the usual way). However, I also need the result row count for the individual SELECT statements. The query, simplified:

(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

If SQL_CALC_FOUND_ROWS is placed in every SELECT statement an "Incorrect usage/placement of 'SQL_CALC_FOUND_ROWS'" error is issued. Google this a lot, read related messages here, to no avail. Might be something really simple, I just can't get my mind arround it. Many thanks.

A: 

You're getting that error because SQL_CALC_FOUND_ROWS can be used on a query to return a single number into FOUND_ROWS().

You can get back counts doing this:

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

if that helps.

If you want to return the rows from the tables with a count then modify it:

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

From your question, it's not precisely clearly what you're trying to achieve.

cletus
Thanks. I'm trying to get the number of results for each individual select, ALONG with the total number if results (that's why I used SQL_CAL_FIND_ROWS and it works neatly). Gave your first solution a try, and ran into this: http://bugs.mysql.com/bug.php?id=43912. If I'd manage to circumvent it, that would probably be it. The second solution works a charm, but involves a nested query with possible performance penalty (not sure how severe, working on a small database now), because the original WHERE clause is a lot more elaborate (id>1000 is just an example). Any thoughts? Thanks again.
Webmaster
Forgot to mention: also, second solution is inconvenient because I need counts separately, NOT in every row.
Webmaster
Accepted the second solution as the closest to what I need, although it places counts in each row, but due to LIMIT there are counts the are not returned (because *rows* containing them are not returned). A combination of the two would have been ideal, if not for the above mentioned bug. Gave up, will do counting in separate queries. Thank you.
Webmaster