tags:

views:

48

answers:

2

In the following query:

SELECT column1,column2 FROM table1 ORDER BY column1 LIMIT 0,30

How can I find out the number of rows that would have been returned were it not for the LIMIT?

Edit: I am looking for a way to work this into the query above and not do a separate query. (If possible.)

+3  A: 
SELECT COUNT(*) FROM table1;
Johan
Is this part of my query above, or a separate query? I knew how to do this... I was hoping for a way to work it into my existing query.
George Edison
@George Edison: Separate query - standard SQL requires you to define a GROUP BY clause for columns that don't use aggregate functions (COUNT, MIN, MAX, etc) in the SELECT clause, which would affect your resultset.
OMG Ponies
What would that look like anyway?
George Edison
well, you could do it like: SELECT column1,column2, (SELECT COUNT(*) FROM table1) AS rows FROM table1 ORDER BY column1 LIMIT 0,30;but I think that is less efficient.
Johan
@Johan: True, but it's going to add the same value to every row returned.
OMG Ponies
Could you create a view using OP's query and use this on the view? If not, a nested query would be the way to go.
rownage
A: 

If you do this query:

 SELECT SQL_CALC_FOUND_ROWS column1,column2 FROM table1 ORDER BY column1 LIMIT 0,30;

You can retrieve the number of rows the previous SELECT found with

select FOUND_ROWS();

If you really must do it with one query, you'll have to use a sub select (which'll have the disatvantage of adding an extra column to every row..)

 SELECT column1,column2,s.total FROM table1,
    (select count(*) as total from table1) s 
 ORDER BY column1 LIMIT 0,30;
nos
http://www.mysqlperformanceblog.com/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/
OMG Ponies
Ah, this looks like what I'll have to do.
George Edison