开发者

find number of rows without using count() in mysql

Can anybody help me to find way to count number of rows found while running query. I want to run this query in stored procedure depending on the count i want to perform certain actions. I was trying to set variable value something like.

 Select abc_master_id,
        abc_name,
        abc_parent_id,
       (@row := @row +1)  rownum 
 from abc_master 
 where blah..  blah.. limit 18,9

Above query is completely wrong. But here I want to count or set some flag that records found are less than or equal to limit set to query i.e here 9. By开发者_JAVA技巧 doing this i will save one query for counting rows fetched by query.

I have tried using SQL_CALC_FOUND_ROWS and Found_rows() but it gives me total number of rows if query run without limit.


The solution:

SELECT abc_master_id, 
       abc_name,
       abc_parent_id,
       @i:=@i+1 AS rownum 
FROM abc_master ,(SELECT @i:=0) foo
where blah.. blah.. limit 18,9


Replace your query with a similar one

Select count(*)
from abc_master where blah.. blah..

and fetch the first row.

Mysql has improved over the years but I don't know if your engine supports the much simpler subquery:

select count(*) from (
Select abc_master_id, abc_name, abc_parent_id ... from abc_master
where blah.. blah..)

Thus: your original query but without the limit clause, between parens.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜