简体   繁体   中英

SQL select by using limit or using program to fetch special records

I am using php to get special records from Database.
which one is better?
1.

Select * From [table] Limit 50000, 10;
while($row = $stmt->fetch()){
     //save in array, total 10 times
}

or 2.

Select * From [table];
$start = 50000;
$length = 10;
while($row = $stmt->fetch()){
     if($i < $start+$length && $j >=$start){
          //save in array, total 50010 times
     }
}

In this case, which one should I use?
Which one using DB with less resources?

which one is better?

Too vague: what is "better"?

Which one using DB with less resources?

You're much better off with the first approach. It's efficient to select as little data as you need and no more. Selecting the whole table will force your script to use a lot more memory because all that data needs to be kept live

The best answer you'll get is: test! You can run your queries multiple times in multiple ways and see for yourself. Just use SELECT SQL_NO_CACHE... instead of the generic SELECT... to force the DB to restart the work from scratch. Measure how long it takes to run the query and process results

function wayOne(){
    //  execute your 1st query and loop through results
}
function wayTwo(){
    // execute 2nd query and loop through results
}

//Measures # of milliseconds it takes to execute another function
function timeThis(callable $callback){
    $start_time = microtime();
    call_user_func($callback);

    $microsecs = microtime()-$start_time; //duration in microseconds    
    return round($microsecs*1000);//duration in milliseconds
}

$wayOneTime = timeThis('wayOne');
$wayTwoTime = timeThis('wayTwo');

You can then compare the two times. Generally (not always) a process that takes significantly less time uses fewer resources

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