2009-06-11 60 views
45

我想爲1行和60行之間選擇的每行生成一個隨機整數作爲計時器。如何獲取mysql隨機整數範圍?

SELECT downloads.date, products.*, (FLOOR(1 + RAND() * 60)) AS timer 

我已經搜索並繼續找到這個FLOOR函數,如何選擇一個範圍內的隨機整數。這給了我每行1。 我錯過了什麼?

我在MySQL 5.0.75

繼承人的其餘查詢本人相信這可能是一個嵌套問題

SELECT * 
FROM (
SELECT downloads.date, products.*, FLOOR(1 + (RAND() * 60)) AS randomtimer, 
(
SELECT COUNT(*) 
FROM distros 
WHERE distros.product_id = products.product_id 
) AS distro_count, 

(SELECT COUNT(*) FROM downloads WHERE downloads.product_id = products.product_id) AS true_downloads 

FROM downloads 
INNER JOIN products ON downloads.product_id = downloads.product_id 
) AS count_table 
WHERE count_table.distro_count > 0 
AND count_table.active = 1 
ORDER BY count_table.randomtimer , count_table.date DESC LIMIT 10 

回答

80

這對我很有用。你的mysql版本可能?

SELECT id, (FLOOR(1 + RAND() *60)) AS timer 
FROM users 
LIMIT 0 , 30 
2

我運行您的查詢,它確實給我一個隨機數對於每一行....可能與隨機(計時器)的名稱有關?

0

RAND函數的輸出將總是0 之間的值。

試試這個:

SELECT downloads.date, products.*, (CAST(RAND() * 60 AS UNSIGNED) + 1) AS timer 
+0

這給了我一個語法錯誤。 – kevzettler 2009-06-12 00:32:04

0

可以增加乘以表中的記錄數數。

SELECT id, 

(FLOOR((SELECT MIN(id)      FROM your_table) + RAND() * 1000000)) AS timer 
FROM your_table 
LIMIT 0 , 30