私の問題はほとんど自明ですが、可能な限り効率的にするためにそれをうまく解決することはできません。
MySQLデータベースからランダムなエントリを選択したい。できるだけ速く、できるだけ効率的にしたいと思っています(それが常に目標ですよね?)。その行を選択するときに、別の行を選択したいのですが、前の行と同じではありません。10行を選択した場合、11行目を他のすべての行とは異なるものにします(一意としましょう:))。しかし、行が足りなくなったら、「エラーを報告」したいと思います。
問題の核心にたどり着くため。MySQLでPHPを使用しています。すでに選択されているタイトルを含む入力配列があります。次に、データベース内のすべてのアイテムの数を取得するので、「最大ループ」を何回実行できるかがわかります。コードを貼り付けて、ここで何を扱っているかを見てみましょう。
try
{
$db = new PDO("mysql:host=localhost;dbname=xxxxx;charset=utf8", "xxxx", "xxxx");
$played = explode(":;:", $_POST['items']); //All already selected items are in $_POST separated by :;:
$sql = "SELECT count(id) AS count FROM table"; //Lets get the total count of items
$query = $db->prepare($sql);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
$count = $result['count']; //There we are...
$i = 0; //Index counter so we dont exceed records.. well kinda (more on that below)
do //do while because we want something to be selected first
{
$sql = "SELECT FLOOR(RAND() * COUNT(*)) AS offset FROM table"; //From here
$query = $db->prepare($sql);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
$offset = $result['offset'];
$sql = "SELECT itemXML FROM table LIMIT $offset, 1";
$query = $db->prepare($sql);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC); //To here is some code to randomly select a record "as efficiently as possible"..
$output = Array();
$xml = simplexml_load_string($result['itemXML']);
$i++;
} while (in_array($xml->{"title"}, $played) && $i < $count); //While record title is in array and while we have not exceeded the total number of records (that's the logic but it isint that simple is it?)
if ($i >= $count)
{
die("400"); //Just a random status code which I parse with the client.
}
$itemArr = Array("whatever" => $xml->{"whatever-attr"}, "title" => $xml->{"title"});
array_push($output, $itemArr); Lets push this to out array
echo json_encode($output); //Aaaaand finally lets print out the results
}
catch (Exception $e) //If anything went wrong lets notify our client so he can respond properly
{
$output = Array("error" => $e->getMessage());
die(json_encode($output));
}
はい、そうですね。問題は、レコードが10個ある場合、9行が選択され、インデックスカウンター$i
が10以上になり、ランダムレコードがすべて配列に含まれることです。次に、選択されるべきであるが選択されていない行が1つあります。
そして、どうすればこれを修正できますか?あなたの助けは大歓迎です!
私がそれを十分に説明しなかったならば、私がもっと一生懸命に努力することを私に知らせてください。