title: How to optimize a code for selecting a limited number of items
body: <p>there is a database which contains two tables that are important for this task:</p>
  
  <ul>
  <li><strong>items</strong> which contains all data related to items that are displayed on a web page</li>
  <li><strong>views</strong> which holds the number of views for those items</li>
  </ul>
  
  <p>The task is to retrieve 50 items with the highest number of views and then display random 10 of them. The current solution seems a bit ineffective as it retrieves full information for those 50 items from the database only to shuffle the results, display first 10 of them and discard the rest. Is there any more efficient way to handle this, preferably through optimizing the database query?</p>
  
  <pre><code>$query  = "SELECT items.*, (SELECT items_views.views FROM items_views WHERE items_views.item = items.id) as views FROM items ORDER BY views DESC LIMIT 0, 50";
  $result = mysqli_query($conn, $query);
  
  $final_array = array();
  while($row = mysqli_fetch_assoc($result)) {
      $final_array[] = $row;
  }
  
  if(is_array($final_array)) {
      $amount_to_display = 10;
      $result_count = 0;
  
      shuffle($final_array);
  
      foreach($final_array as $final_row) {
          // display the results here
          if (++$result_count &gt;= $amount_to_display) break;
      }
  }
  </code></pre>