我有如下的mysql数据库结构:
CREATE TABLE test (
id int(11) NOT NULL auto_increment,
title text NULL,
tags text NULL,
PRIMARY KEY (id)
);
字段标签上的数据存储为以逗号分隔的文本,例如html,php,mysql,网站,html等。
现在,我需要创建一个数组,其中包含从随机记录中随机选择的大约50个标签。
目前,我正在使用rand()从数据库中选择15个随机mysql数据,然后从数组中的15条记录中保存所有标签。然后,我使用array_rand()将数组随机化,并仅选择50个随机标签。
$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()的执行速度非常慢,有时无法正常运行。任何人都可以让我知道如何正确处理这种情况,以便我的页面正常工作。
最佳答案
永远不要ORDER BY RAND()
-这对于性能来说是可怕的。而是在PHP中进行随机化。由于您的ID是自动递增的(可能不是最好的方法),因此如下所示:
$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)");
顺便说一句,为什么要将标签放在字符串列表中,以便以后再爆炸该字符串?从一开始就将它们放入数组中。