1

What I am trying to get is to send a request to DB that will:

1 count all rows
2 return 10 rows

SELECT count( * ) AS 'total'
FROM stuff
WHERE usr = '65'
LIMIT 10 

So it is supposed to return 10 results PLUS 'total' with the number of all rows. So far it returns the counted amount of rows only....

StuartLC
  • 104,537
  • 17
  • 209
  • 285
Rossitten
  • 1,140
  • 1
  • 16
  • 34
  • 3
    not possible. you cannot mix aggregate functions with "normal" data like that. easier to run two separate queries. – Marc B Feb 05 '14 at 04:09
  • if you set a limit of 10, why do you need to count it? – KyleMassacre Feb 05 '14 at 04:10
  • 1
    @KyleMassacre COUNT isn'T affected by the LIMIT clause, it always counts all rows. – Johannes H. Feb 05 '14 at 04:11
  • @KyleMassacre - I need ALL rows in table to be counted but ONLY 10 to be returned... anyway - looks like it's not posisle in one go... =( – Rossitten Feb 05 '14 at 04:13
  • To expand on what MarcB said, the basic problem is that your `stuff` table has multiple columns, and those columns are incompatible with just a single integer like `COUNT` returns. A `UNION` might have been feasible if the columns were compatible types in both queries. – jpmc26 Feb 05 '14 at 04:13
  • http://dev.mysql.com/doc/refman/5.5/en/information-functions.html#function_found-rows – CBroe Feb 05 '14 at 04:14

3 Answers3

2

You'll need to split the 2 concerns out, and then recombine them:

SELECT s.col1, s.col2, s.col3, x.total
FROM `stuff` s
CROSS JOIN 
(
   SELECT count(*) AS total
   FROM `stuff`
   WHERE `usr` = '65'
) x
WHERE s.`usr` = '65'
LIMIT 10;

Fiddle here RDBMs like SqlServer and Oracle allow for CTE's which would allow you to DRY up the repeated select ... where. Some options in MySql here

Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285
2
-- count records first
SET @total = (
    SELECT count( * ) AS 'total'
    FROM `stuff`
    WHERE `usr` = '65'
);

-- then, select your ten records and include the total from previous operation
SELECT *, @total
FROM `stuff`
WHERE `usr` = '65'
LIMIT 10 
Alex
  • 34,899
  • 5
  • 77
  • 90
0

If you want all rows to be counted and limit the result to 10 then you can do it the following way

SELECT SQL_CALC_FOUND_ROWS * FROM `stuff` WHERE `usr` = '65' LIMIT 10 
SELECT FOUND_ROWS(); 
Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207