【发布时间】:2010-04-20 16:27:59
【问题描述】:
我的mysql数据库结构如下:
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 个从随机记录中随机选择的标签。
目前我正在使用 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() 执行速度非常慢,有时它不起作用。那么谁能告诉我如何正确处理这种情况,以便我的页面正常工作。
【问题讨论】:
-
分布是否需要尽可能统一? 15 条记录的限制是常数吗?
-
不。我只需要大约 10-15 个随机记录来确保我最终会得到 50 个随机标签。