我的问题几乎是不言自明的,但我不能完全解决它以使其尽可能高效。
我想从 MySQL 数据库中选择一个随机条目。我希望它尽可能快且尽可能高效(这始终是目标,不是吗?)。当我选择该行时,我想选择另一行,但与之前的行不同。如果我选择 10 行,我希望第 11 行与所有其他行不同(可以说是唯一的 :))。但是当我用完行时,我想“报告错误”。
才能触及问题的核心。我正在使用 PHP 和 MySQL。我有一个包含已选择标题的输入数组。然后我得到数据库中所有项目的计数,所以我知道我可以“循环通过最大值”多少次。让我们粘贴代码来看看我们在这里处理什么。
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 并且随机记录都在数组中,该怎么办?然后我们有一行应该被选中,但它没有。
我该如何解决这个问题?您的帮助将不胜感激!
如果我解释得不够好,请告诉我,我会更加努力。