我有一个大约有70列和120000行数据的表。我想做的是随机化一条记录,然后显示该记录的其他列的值。如果我提取了所有数据,
$result=mysqli_query($link, 'SELECT id, column1, column2, column3, ..., column 70 from table');
while ($row=mysqli_fetch_array($result))
{
$info[] = array('id'=>$row['id'], 'column1'=>$row['column1'], ...);
}
$randindex = rand(0,count($info));
$id = $info[$randindex]['id'];
echo $info[$randindex]['column1']; echo $info[$randindex]['column2']; ....
恐怕这将大大减缓进程。因此,我想在随机化之前只查询ID,然后使用随机化的ID来检索数据库中该记录的其他值。
$result=mysqli_query($link, 'SELECT id from table');
while ($row=mysqli_fetch_array($result))
{
$info[] = $row['id'];
}
$randindex = rand(0,count($info));
$id = $info[$randindex];
然后以某种方式检索该特定记录的所有其他字段。我在这里问过如何在SQL中做到这一点,但我想知道除了SQL之外,是否还有其他更有效的方法。我需要做这样的循环吗?
在代码中,执行以下操作:
select min(id) as minid, max(id) as maxid
from table;
然后使用php生成一个随机id
并执行:
select t.*
from table t
where t.id >= $randid
order by id
limit 1;
有了id
上的索引,以及关于值之间没有太大差距的合理假设,这将很好地工作。
你可以在一个查询中做同样的事情:
select t.*
from table t cross join
(select min(id) as minid, max(id) as maxid from table) tt
where t.id >= minid + rand() * (tt.maxid - tt.minid)
order by id
limit 1;
您可以在sql查询中直接使用ORDER BY RAND()
:
SELECT * FROM table ORDER BY RAND() LIMIT 1
ORDER BY RAND()
实际上对行进行了随机排序,然后只进行LIMIT 1
,只得到一行,即第一行。
我认为这是无效的。我认为使用ORDER BY RAND()只执行一个查询会更快