php - 使用 PHP 从数据库中选择一个随机行,但不相等

标签 php mysql database arrays

我的问题几乎是不言自明的,但我无法完全解决以使其尽可能高效。
我想从 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 并且随机记录都在数组中会怎样。然后我们有一行应该被选中但没有被选中。

我该如何解决这个问题?非常感谢您的帮助!
如果我解释得不够好,请告诉我,我会更加努力。

最佳答案

我认为您在这里采用了错误的方法。您不需要遍历数据库一次查询一条记录。

如果需要选取10条记录,像这样选取RAND()排序的10条记录即可

SELECT * FROM table
ORDER BY RAND()
LIMIT 10;

或者,如果您希望从选择中忽略某些 ID

SELECT * FROM table
WHERE id NOT IN (?, ?, ?, ...)
ORDER BY RAND()
LIMIT 10;

或者如果你想省略的 id 存储在另一个表中

SELECT * FROM table
LEFT OUTER JOIN omit_table ON table.id = omit_table.id
WHERE omit_table.id IS NULL
ORDER BY RAND()
LIMIT 10;

关于php - 使用 PHP 从数据库中选择一个随机行,但不相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15277684/

相关文章:

c++ - 如何监控应用程序的数据库更新?

mysql - Perl DBI 创建表错误

MySQL Select 查询返回错误行

c# - MySqlDataReader dataReader =cmd.ExecuteReader() 不进入while循环弹出窗口Form

php mysql select,数组结果内部数组结果

php - Magento:是什么导致重新索引……为什么它会中断?

mysql - 尝试设计一个在线学生练习数据库

php - laravel 中用于支付网关的 csrf 异常

php - 获取 PHP 语言区域设置日期 - 2022

php - 使用php动态地将内容插入到pdf文件中