所以这就是我的使命:从没有主键的MySQL表中返回一个随机行。快速搜索返回this page和此解决方案:
SELECT column FROM table
ORDER BY RAND()
LIMIT 1;
不幸的是,该解决方案没有得到优化,因为this site表明了这一点。他们提出了以下修复:PHP:
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `table` ");
$offset_row = mysql_fetch_object( $offset_result );
$offset = $offset_row->offset;
$result = mysql_query( " SELECT * FROM `table` LIMIT $offset, 1 " );
我已经在页面上发布了这个,但同时我需要在原始的MySQL中尝试它。所以我打了一拳:
SELECT *
FROM `table`
LIMIT (SELECT FLOOR(RAND() * COUNT(*)) FROM `table`), 1;
...并收到以下错误:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT FLOOR(RAND() * COUNT(*)) FROM `table`), 1' at line 3
但我不明白,因为各个组件都能完美运作。如果我输入:
SELECT FLOOR(RAND() * COUNT(*))
FROM `table`
...我得到一个从0到行数减去1的随机数。同样,如果我输入:
SELECT *
FROM `table`
LIMIT 2, 1
...我得到了表格中的第三行(如果我将3替换为2,则为第四行等)
我做错了什么?提前谢谢!
答案 0 :(得分:0)
如果您想要随机抽样,以下内容可能足够快:
SELECT *
FROM `table` t cross join
(select count(*) as cnt from table t) const
WHERE rand() <= 100 / cnt
ORDER BY rand()
LIMIT 1 ;
这必须扫描表格,但排序大约有100行,这应该足够快。