我有下表(包含超过一百万行):
**MyTable**
id - int(10)
externalId - smallint(5)
description - varchar(250)
status - smallint(6)
entrydate - int(10) (unix timestamp)
我希望能够从此表中选择一个随机行(我只需要结果集中的id值),并带有以下where子句:
/* The number of external ids here can range from 1 to around 50 */
WHERE externalId in (1,2,3,4,x,x,x)
/* Status is fixed at 2 for all calls */
AND status = 2
/* Entry date is typically (now - 30 days) or may be excluded all together */
AND entrydate > 1279887765
显而易见的解决方案是使用rand()但是我发现它的性能有点缺乏,这是相当好的记录。那么有人有任何替代解决方案吗?
提供一些背景知识:我打算在PHP驱动的网站上使用此查询,输入参数取决于用户,因此这些将随用户而变化。值得一提的是,我根本无法改变表结构。
提前致谢。
答案 0 :(得分:1)
当你说,你使用PHP时,为什么不用这种语言呢?
假设您知道您有100.000行,在PHP中生成一个在此范围内的随机数,并执行LIMIT查询
SELECT * FROM mytable ORDER BY id LIMIT $randomNumber, 1;
答案 1 :(得分:0)
您可以执行两个查询 - 一个用于获取总可能行数,然后使用该计数在PHP中生成从零到($ count - 1)的随机整数,然后添加“LIMIT $ rand,1”到第二个查询的结尾。