Query Optimization: Which SELECT syntax is faster?

Given the 5000 identifiers of records in the database, which query, in your opinion, is faster?

  • Scroll through 5000 identifiers with php and execute a SELECT query for each of them,

    foreach($ids as $id){
      // do the query 
      $r = mysql_query("SELECT * FROM TABLE WHERE ID = {$id}");
    }
    
  • Or collect all identifiers in an array and use SELECT * FROM TABLE WHERE ID IN (from 1 to 5000)

    //assuming $ids = array(1,2 ---- up to 5000);
    $r = mysql_query("SELECT * FROM TABLE WHERE ID IN (".join(",",$ids).")");
    
+3
source share
7 answers

Without a shadow of a doubt, downloading them all at once will be faster. Running 5,000 requests will be much slower, as each request will incur a certain amount of overhead.

, , *! , , , ! , , , .

+4

2 . 5000 db .

+4

- 5000 .
100, . 5000 -

+2

, , , . , , , .

0

Loop , . ; .

, SQL; .

0

2 . 1 roundtrim .

, .

: , , . , 10 , .

0

?
, , :

<?php
    $start = getmicrotime();
    for ($i=0;$i<100000;$i++)
    {
            foreach($ids as $id){
              // do the query 
              $r = mysql_query("SELECT * FROM TABLE WHERE ID = {$id}");
            }

    }
    $end = getmicrotime();
    echo 'Time (1): '.($end- $start).' sec';



    $start = getmicrotime();
    for ($i=0;$i<100000;$i++)
    {
            //assuming $ids = array(1,2 ---- up to 5000);
            $r = mysql_query("SELECT * FROM TABLE WHERE ID IN (".join(",",$ids).")");
    }
    $end = getmicrotime();
    echo 'Time (2): '.($end- $start).' sec';
?>
0

Source: https://habr.com/ru/post/1758167/


All Articles