MySQL DB에서 무작위로 SELECT를 할 필요가 없습니다. 연구를 한 후에 RAND()를 사용하는 것은 나쁜 생각이라고 일반적인 사람들이 말하는 것 같습니다. 다른 유형의 임의 선택을 수행하는 방법을 설명하는 기사를 발견했습니다.Kohana의 MySQL 쿼리에서 RAND()를 사용하지 않기 3
기본적으로 5 개의 무작위 요소를 선택하려면 다음을 수행해야합니다. 여기에서 Kohana 프레임 워크를 사용하고 있습니까?
<?php
final class Offers extends Model
{
/**
* Loads a random set of offers.
*
* @param integer $limit
* @return array
*/
public function random_offers($limit = 5)
{
// Find the highest offer_id
$sql = '
SELECT MAX(offer_id) AS max_offer_id
FROM offers
';
$max_offer_id = DB::query(Database::SELECT, $sql)
->execute($this->_db)
->get('max_offer_id');
// Check to make sure we're not trying to load more offers
// than there really is...
if ($max_offer_id < $limit)
{
$limit = $max_offer_id;
}
$used = array();
$ids = '';
for ($i = 0; $i < $limit;)
{
$rand = mt_rand(1, $max_offer_id);
if (!isset($used[$rand]))
{
// Flag the ID as used
$used[$rand] = TRUE;
// Set the ID
if ($i > 0) $ids .= ',';
$ids .= $rand;
++$i;
}
}
$sql = '
SELECT offer_id, offer_name
FROM offers
WHERE offer_id IN(:ids)
';
$offers = DB::query(Database::SELECT, $sql)
->param(':ids', $ids)
->as_object();
->execute($this->_db);
return $offers;
}
}
그렇지 않은 경우 더 나은 해결책은 무엇입니까?
예,이 코드의 형식은 Kohana 3입니다. –
처리중인 행의 수는 얼마입니까? RAND()가 나쁘다는 이유로 나를 기사로 연결할 수 있습니까? –