使用 php & 的随机数据mysql [英] random data using php & mysql

查看:37
本文介绍了使用 php & 的随机数据mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的mysql数据库结构如下:

I have mysql database structure like below:

CREATE TABLE test (
    id int(11) NOT NULL auto_increment,
    title text NULL,
    tags text NULL,
    PRIMARY KEY (id)
);

字段标签上的数据存储为逗号分隔的文本,如 html、php、mysql、website、html 等...现在我需要创建一个数组,其中包含从随机记录中随机选择的大约 50 个标签.

data on field tags is stored as a comma separated text like html,php,mysql,website,html etc... now I need create an array that contains around 50 randomly selected tags from random records.

目前我正在使用 rand() 从数据库中选择 15 个随机的 mysql 数据,然后将 15 个记录中的所有标签保存在一个数组中.然后我使用 array_rand() 随机化数组并只选择 50 个随机标签.

currently I am using rand() to select 15 random mysql data from database and then holding all the tags from 15 records in an array. Then I am using array_rand() for randomizing the array and selecting only 50 random tags.

$query=mysql_query("select * from test order by id asc, RAND() limit 15");
$tags="";
while ($eachData=mysql_fetch_array($query)) {
    $additionalTags=$eachData['tags'];
    if ($tags=="") {
        $tags.=$additionalTags;
    } else {
        $tags.=$tags.",".$additionalTags;
    }
}

$tags=explode(",", $tags);
$newTags=array();
foreach ($tags as $tag) {
    $tag=trim($tag);
    if ($tag!="") {
        if (!in_array($tag, $newTags)) {
            $newTags[]=$tag;
        }
    }
}

$random_newTags=array_rand($newTags, 50);

现在我在数据库上有大量记录,因此;rand() 执行速度非常慢,有时不起作用.那么谁能告诉我如何正确处理这种情况,以便我的页面正常工作.

Now I have huge records on the database, and because of that; rand() is performing very slow and sometimes it doesn't work. So can anyone let me know how to handle this situation correctly so that my page will work normally.

推荐答案

从不 ORDER BY RAND() - 这对性能来说很糟糕.而是在 PHP 中进行随机化.像这样,因为您的 ID 是自动递增的(可能不是最好的方法):

Never ORDER BY RAND() - it's horrible for performance. Instead do the randomizing in PHP. Something like this, since your ID is auto incrementing (may not be the best approach):

$count = mysql_fetch_assoc(mysql_query("select count(1) as count from test"));
$range = range(0, $count['count']);

$selection = array_rand($range, 50);
$sel_list = implode(',', $selection);

$query = mysql_query("select * from test where id in ($sel_list)");

顺便说一下,为什么你把你的标签放在一个字符串列表中,只是为了稍后分解那个字符串?只需从一开始就将它们放入一个数组中.

By the way, why are you putting your tags in a string list, only to explode that string later? Just put them into an array from the start.

这篇关于使用 php & 的随机数据mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆