adding count( ) column on each row

This won't add the count to each row, but one way to get the total count without running a second query is to run your first query using the SQL_CALC_FOUND_ROWS option and then select FOUND_ROWS(). This is sometimes useful if you want to know how many total results there are so you can calculate the page count.

Example:

select SQL_CALC_FOUND_ROWS ID, Title, Author
from yourtable
limit 0, 10;
SELECT FOUND_ROWS();

From the manual: http://dev.mysql.com/doc/refman/5.1/en/information-functions.html#function_found-rows


The usual way of counting in a query is to group on the fields that are returned:

select ID, Title, Author, count(*) as Cnt
from ...
group by ID, Title, Author
order by Title
limit 1, 10

The Cnt column will contain the number of records in each group, i.e. for each title.


Regarding second query:

select tbl.id, tbl.title, tbl.author, x.cnt
from tbl
cross join (select count(*) as cnt from tbl) as x

If you will not join to other table(s):

select tbl.id, tbl.title, tbl.author, x.cnt
from tbl, (select count(*) as cnt from tbl) as x

Tags:

Mysql

Sql