[英]Mysql: 'order by Rand() Limit 4 ' or not?
i need to extract random 4 items from latest news database. 我需要从最新新闻数据库中随机抽取4个项目。
since this table has a lot of rows. 因为该表有很多行。 is it wise to do so with order by RAND() or its waste of resources ?-since it will go thro the whole table and reorder it ?
用RAND()进行排序或浪费资源是否明智?因为它将遍历整个表并对它重新排序?
is there a better way to do it ? 有更好的方法吗? extract random featured items from table with hundreds of rows ?
从具有数百行的表中提取随机特征项?
Example: 例:
$l=$database->query("SELECT car,price,thumbnail FROM cardb WHERE type='new' order by RAND() LIMIT 4");
foreach($l as $l){print_r($l);}
Thankx for taking time to answer } 感谢您抽出时间来回答}
Well... I would do this in two queries. 好吧...我将在两个查询中执行此操作。 Get random row numbers:
获取随机行号:
SELECT
floor(count * rand()) r1,
floor(count * rand()) r2,
floor(count * rand()) r3,
floor(count * rand()) r4
FROM
(SELECT count(*) count FROM cardb WHERE type = 'new') c
And get rows: 并获取行:
SELECT car, price, thumbnail FROM cardb WHERE type = 'new' LIMIT {r1}, 1
UNION ALL
SELECT car, price, thumbnail FROM cardb WHERE type = 'new' LIMIT {r2}, 1
UNION ALL
SELECT car, price, thumbnail FROM cardb WHERE type = 'new' LIMIT {r3}, 1
UNION ALL
SELECT car, price, thumbnail FROM cardb WHERE type = 'new' LIMIT {r4}, 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.