简体   繁体   中英

Is it possible to combine the following two SQL statements into one?

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.

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();

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM