我有一张包含超过300,000条记录的表格。我需要从此表中选择10或13或20条记录。
我尝试过以下方法。
这需要很长时间才能选择
SELECT * FROM products ORDER BY RAND() LIMIT 0,12
OR
这种方式相同,但我似乎无法选择多于1条记录
$temp = mysql_query('SELECT id FROM products limit 0,12');
if ( count( $temp ) > 0 ) {
$j = 1;
foreach( $temp as $index => $row ) {
$p[$j++] = $row[id];
}
$my_p= $p[ rand( 1, --$j ) ];
$pp = 'SELECT id FROM products WHERE id = {$my_p}';
}
更新: 在此MySQL select 10 random rows from 600K rows fast
之后我有
SELECT * FROM QM_Products AS r1
JOIN (SELECT (RAND() * (SELECT MAX(id)
FROM QM_Products )) AS id) AS r2 WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 0, 10
这项工作谢谢大家。
答案 0 :(得分:1)
试试这个PHP代码
$r = mysql_query("SELECT count(*) FROM user");
$d = mysql_fetch_row($r);
$rand = mt_rand(0,$d[0] - 1);
$r = mysql_query("SELECT username FROM user LIMIT $rand, 1");
答案 1 :(得分:1)
您选择使用此解决方案:
SELECT * FROM QM_Products AS r1
JOIN (SELECT (RAND() * (SELECT MAX(id)
FROM QM_Products )) AS id) AS r2 WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 0, 10
但是,我会指出,如果随机表达式返回接近表末尾的id,则可以少于10行。
此外,这不是一个随机选择,因为返回的行将始终具有相邻的id值。
除了ORDER BY RAND()
解决方案(当然这对大型数据集表现不佳,因为它不能使用索引),我可以想到另一种随机选择多行的方法。这是一些伪PHP代码:
// MAX(id) is quicker than COUNT(*) in InnoDB
$maxid = query "SELECT MAX(id) FROM QM_Products"
// generate a list of N random values, making sure they're distinct
$id_list = array();
while (count($idlist) < 10) {
$rand_id = mt_rand(1,$maxid);
$id_list[$rand_id] = 1;
}
// convert the id list to a comma-separated string in an SQL query
$id_list = implode(",", array_keys($id_list));
$rows = query "SELECT * FROM QM_Products WHERE id IN ($id_list)"
如果随机值达到没有存在匹配id的行的间隙,则可能会少于N行。但是上述方法比ORDER BY RAND()
快得多,或者一次发出1行N次查询。因此,您可以根据需要设计循环以重复搜索以查找N行。如果你有很大的间隙,那就不好了,因为它可以在找到足够的行之前循环很长时间。