1

I need get specific values and count all values from a MySQL table, i need get the best performance, my question is: What is better and faster?

- Use two separate queries:

 $TBCount = $Resps = $MySQL->query('SELECT COUNT(*) FROM T1');
 $Resps = $MySQL->query('SELECT id, name FROM T1 LIMIT 1');
 while ($Resp = $Resps->fetch_assoc()) {
    ...
 }

- Use One query with two SELECT:

 $Resps = $MySQL->query('SELECT id, name, (SELECT COUNT(*) FROM T1) AS count FROM T1 LIMIT 1');
 while ($Resp = $Resps->fetch_assoc()) {
    $TBCount = $Resp['count'];
    ...
 }

- Or someone have some best idea?

In the case of "One query, two SELECT", in the "while" loop, how can i get the count value outside of the loop? (to avoid unnecessary rewrite of the variable).

Mike
  • 23,542
  • 14
  • 76
  • 87
Manux22
  • 323
  • 1
  • 5
  • 16

3 Answers3

1

I would suggest first option with minor modification.

 $TBCount = $Resps = $MySQL->query('SELECT COUNT(id) FROM T1');
 $Resps = $MySQL->query('SELECT id, name FROM T1 LIMIT 1');
 while ($Resp = $Resps->fetch_assoc()) {
    ...
 }

note that I have mentioned just id in count query, this can be a good performance impact while dealing with large data.

You can do the same in second option, but as per my thought process second option will give count in all row returned with the main query. And that value will be same for all rows which is really not required.

That is the reason I would go with first option for separate queries.

Avinash
  • 6,064
  • 15
  • 62
  • 95
0

Take a look at SQL_CALC_FOUND_ROWS. It does everything you want. It will give you the total results, even though you're limiting the data returned.

> SELECT SQL_CALC_FOUND_ROWS id, name FROM T1 LIMIT 1
> SELECT FOUND_ROWS();
iamdev
  • 716
  • 4
  • 13
  • In the `SELECT` query, i not take all values, filter with LIMIT, and need count ALL values from table. – Manux22 May 29 '15 at 03:58
  • Easy fix. Just use column names instead of *. – iamdev May 29 '15 at 04:02
  • This will work like a charm but have u considered the time it would take. better to go with separate query for count and result. – Avinash May 29 '15 at 04:08
  • 1
    ref: http://stackoverflow.com/a/188682/148478 and https://www.percona.com/blog/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/ – Avinash May 29 '15 at 04:21
0
$Resps = $MySQL->query('SELECT id, name, (SELECT COUNT(*) as tot FROM T1) AS count FROM T1 LIMIT 1');
$Resp = $Resps->fetch_assoc()
$TBCount = $Resp['tot'];
mysqli_data_seek($Resps, 0);

for finding the count value you do not need to repeatedly loop again and again for the rest of the values use the while loop.

while ($Resp = $Resps->fetch_assoc()) {
  //rest of your code
    ...
 }
Sourabh Kumar Sharma
  • 2,864
  • 3
  • 25
  • 33