How can the ORDER BY RAND() clause be optimized for better performance in PHP banner rotation scripts?

The ORDER BY RAND() clause can be optimized for better performance in PHP banner rotation scripts by using a different approach to randomizing the results. One way to achieve this is by selecting a random number within the range of the total number of banners and then fetching the corresponding banner from the database. This method avoids the performance issues associated with using ORDER BY RAND() on large datasets.

// Get the total number of banners
$totalBanners = $db->query("SELECT COUNT(*) FROM banners")->fetchColumn();

// Generate a random number within the range of total banners
$randomNumber = mt_rand(1, $totalBanners);

// Fetch the banner corresponding to the random number
$randomBanner = $db->query("SELECT * FROM banners LIMIT $randomNumber, 1")->fetch();