MySQL 如何获得mysql随机整数范围?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/984396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get mysql random integer range?
提问by kevzettler
I am trying to generate a random integer for each row I select between 1 and 60 as timer.
我正在尝试为我在 1 到 60 之间选择作为计时器的每一行生成一个随机整数。
SELECT downloads.date, products.*, (FLOOR(1 + RAND() * 60)) AS timer
I have searched and keep coming up to this FLOOR function as how to select a random integer in a range. This is giving me a 1 for every row. What am I missing?
我已经搜索并不断提出这个 FLOOR 函数,以了解如何在一个范围内选择一个随机整数。这给我每一行一个 1。我错过了什么?
I am on mysql 5.0.75
我在 mysql 5.0.75
Heres the rest of the query I belive it might be a nesting issue
继承人的其余查询我相信它可能是一个嵌套问题
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
回答by Ryan Oberoi
This is working for me. Your mysql version maybe?
这对我有用。你的mysql版本可能吗?
SELECT id, (FLOOR( 1 + RAND( ) *60 )) AS timer
FROM users
LIMIT 0 , 30
回答by Jaime
I'm running your query and it does give me a random number for each row.... maybe has something to do with the name of the random (timer)?
我正在运行您的查询,它确实为每一行提供了一个随机数......也许与随机(计时器)的名称有关?
回答by Chris Morley
The output of the RAND
function will always be a value between 0and 1.
RAND
函数的输出将始终是0和1之间的值。
Try this:
尝试这个:
SELECT downloads.date, products.*, (CAST(RAND() * 60 AS UNSIGNED) + 1) AS timer
回答by e_r_k_a_n e_r_t_u_r_a_l
You can increase the number multiplied by the number of records in the table.
您可以增加乘以表中记录数的数量。
SELECT id,
(FLOOR( (SELECT MIN(id) FROM your_table ) + RAND( ) * 1000000 ) ) AS timer
FROM your_table
LIMIT 0 , 30