tags:

views:

69

answers:

3

There are two SQL statements. One is

select count(*) from steventable where username='steven';
select * from steventable where username='steven' LIMIT 0 , 30;

Is it possible to combine two SQL statements into one? The first one is to get how many records in steventable when username is steven, the second one is to fetch the first 30 records which username is steven.

I am using MySQL.

A: 

Since the second query returns 30 rows; does that mean that you want every single row to also contain the total number of rows? In that case, you'd have to use subqueries

select *, (select count(*) from steventable where username='steven') allSteven from steventable where username='steven' LIMIT 0 , 30;

altho i think it makes more sense to split these up into distinct queries

David Hedlund
A: 
select (select count(*) from steventable where username='steven') AS the_count,
st.* from steventable st where st.username='steven' LIMIT 0 , 30;

I don't know why you need to do that, but can't come up with a good reason to combine those 2 queries into one.

Ivan Krechetov
I want to improve efficiency.
Steven
+1  A: 

Although it's still two statements, using the FOUND_ROWS function and SQL_CALC_FOUND_ROWS should do what you need and will be more efficient than two separate queries.

SELECT SQL_CALC_FOUND_ROWS *
FROM steventable
WHERE username = 'steven'
LIMIT 0, 30;

SELECT FOUND_ROWS();
LukeH
Genius.This is what I exactly want. Thank you, @Luke.
Steven