开发者

How do I select a specific id from a table, and at the same time find out how many rows there in total within just ONE query?

MySQL (table)

+----+--
| id |
+----+--
| 1  |
+----+--
| 2  |
+----+--


$a = mysql_query("SELECT * FROM `table` WHERE `id` = '1'");

I want to select id 1, however, I also want to see how many rows there are in total (in the case above it would 开发者_如何学编程be 2 rows). Is that even possible to do within just ONE query?


You would do this using a subquery

SELECT T.*, (select count(*) FROM `table`) AS total FROM `table` T where id='1'

Hope that helps!


Still technically 2 queries, but only 1 workload:

SELECT SQL_CALC_FOUND_ROWS * FROM table ORDER BY FIELD(id, 1) LIMIT 1;
SELECT FOUND_ROWS();

But SQL_CALC_FOUND_ROWS is not always faster! See http://www.mysqlperformanceblog.com/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/

Instead, I would bite the bullet, and at least take some solace knowing that at least you're doing it in a mysql_multi_query().


Stored Procedure would mean 1 "query".

CALL yourfunction();


The only way I see now is to use subquery with proper main query modifications. SQL queries usually return only one dataset, so you mus be creative with this. ;]

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜