Count rows in MySQL along with the actual row contents

You can use a CROSS JOIN. The subquery will get the count for all firstnames and then it will include this value in each row:

SELECT firstname, d.total
FROM BigTable
CROSS JOIN 
(
   SELECT COUNT(*) total
   FROM BigTable
   WHERE firstname LIKE 'a%'
) d
WHERE firstname LIKE 'a%';

See SQL Fiddle with Demo


You can join with a subquery:

SELECT firstname, ct
FROM BigTable
JOIN (SELECT COUNT(*) ct
      FROM BigTable
      WHERE firstname LIKE 'a%') x ON (1 = 1)
WHERE firstname LIKE 'a%'

The cross join is not the efficient way, the better way is to use an inline SELECT like the following structure:

SELECT firstname, 
       (select count(*) from BigTable where firstname like 'a%') as count 
from BigTable  
where firstname like 'a%'

I tested both approaches with 50k records in database, and this approach is almost 2x faster.

Tags:

Mysql

Count

Rows