2011-10-05 63 views
1

我需要從最新的新聞數據庫中提取隨機4項。Mysql:'蘭德()限制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);} 

Thankx抽出時間來回答 }

+1

的可能重複(http://stackoverflow.com/questions/ 1244555/how-can-i-optimize-mysqls-order-by-rand-function) –

回答

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 

並獲得行:[?如何優化MySQL的ORDER BY RAND()函數]

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 
+0

該查詢可能在結果集中有重複。 'ORDER BY RAND()'不會。 –

+0

@MichaelMadsen是的,但我認爲這不是一個大問題。否則,我們可以在PHP端生成唯一的隨機數。無論如何,我認爲這是最資源優化的解決方案之一。 – Karolis