开发者

get result of two query with one query - mysql

$sql ="select * from user limit 5"; 

is there any way that i can get limited number of results but with total results without limit.

Basically i want result of below two queries in one single query.

query 1 : select count(*) from user
query 2 : select * from user LIMIT 5

is that possib开发者_运维技巧le without any sub query?


select *, '' as total from user limit 5
UNION
select *,count(*) as total from user group by id>0


Maybe a bit late, but the answer can help someone else.

It is possible to tell MySql to return only the first 5 results AND calculate the total number, using SQL_CALC_FOUND_ROWS, as explained here http://www.arraystudio.com/as-workshop/mysql-get-total-number-of-rows-when-using-limit.html

You issue two queries, but in the first one you hint the db engine to calculate and keep the total number of rows that would be returned without the LIMIT clause


How about something like

select  *,
        (select count(*) from user) TotalUsers
from    user 
LIMIT 5 

Or maybe

select  user.*,
        TotalUsers.TotalCnt
from    user,
        (select count(*) TotalCnt from user) TotalUsers
LIMIT 5 


This is a common problem, and as far as I know it just isn't possible.. Stick with two queries, it's fast and clear.


single query not possible if without join or union, however, you can try something like

select sql_calc_found_rows * from user limit 5;
select found_rows();  <-- total from first query
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜