Mysql:'由Rand()限价4'订购还是没有?

时间:2011-10-05 18:51:07

标签: php mysql mysql-management

我需要从最新的新闻数据库中提取随机的4个项目。

因为这个表有很多行。通过RAND()或者浪费资源来做这样的事情是明智的吗? - 因为它会整个表格并重新排序吗?

有更好的方法吗?从表中提取数百行的随机特色项目?

示例:

$l=$database->query("SELECT car,price,thumbnail FROM cardb WHERE type='new' order by RAND() LIMIT 4");
foreach($l as $l){print_r($l);}

感谢你抽出时间回答                                     }

1 个答案:

答案 0 :(得分:0)

嗯......我会在两个查询中执行此操作。获取随机行号:

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

获取行:

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