假设我想从48000行的Db中随机选择5000行,但我想确保30行(我有唯一的ID)是该选择的一部分。有没有办法在MySQL中做到这一点?
id,问题,答案,类别等......
答案 0 :(得分:0)
您可以首先选择您有ID的记录到占位符数组中,然后使用RAND()选择余额。
SELECT * FROM table WHERE id IN (list_of_ids)// put this in array...
SELECT * FROM table WHERE id NOT IN (list_of_ids) ORDER BY RAND() LIMIT 4970// put this in second array...
$myResults = array_merge($array1, $array2);
对于您描述的大小的表格,性能应该没问题......
如Bill所述,您可以使用UNION ...
在一个查询中执行此操作SELECT * FROM table WHERE id IN (list_of_ids)
UNION
SELECT * FROM table WHERE id NOT IN (list_of_ids) ORDER BY RAND() LIMIT 4970