在 MySQL 中插入/更新随机日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4546111/
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
Insert/ Update random date in MySQL
提问by Blair
How would I update a column with a random date in the past 2 weeks using MySQL?
如何使用 MySQL 在过去 2 周内更新具有随机日期的列?
For example (code doesn't actually work):
例如(代码实际上不起作用):
UPDATE mytable
SET col = sysdate() - rand(1, 14);
回答by álvaro González
You can get a random integer with this expression:
你可以用这个表达式得到一个随机整数:
To obtain a random integer R in the range i <= R < j, use the expression
FLOOR(i + RAND() * (j - i))
. For example, to obtain a random integer in the range the range 7 <= R < 12, you could use the following statement:SELECT FLOOR(7 + (RAND() * 5));
要获得 i <= R < j 范围内的随机整数 R,请使用表达式
FLOOR(i + RAND() * (j - i))
。例如,要获得 7 <= R < 12 范围内的随机整数,您可以使用以下语句:SELECT FLOOR(7 + (RAND() * 5));
http://dev.mysql.com/doc/refman/5.1/en/mathematical-functions.html
http://dev.mysql.com/doc/refman/5.1/en/mathematical-functions.html
Use that to generate a random number of days, hours or minutes (depending on the resolution) and add that number to current date. Full expression would be something like this:
使用它来生成随机数的天数、小时数或分钟数(取决于分辨率)并将该数字添加到当前日期。完整的表达是这样的:
SELECT NOW() - INTERVAL FLOOR(RAND() * 14) DAY;
回答by Salman A
UPDATE mytable
SET col = CURRENT_TIMESTAMP - INTERVAL FLOOR(RAND() * 14) DAY
This sets col
to a date between (and including) current date and current date - 13 days. Multiply by 15 to get current date - 14 days.
这将设置col
为(包括)当前日期和当前日期之间的日期 - 13 天。乘以 15 得到当前日期 - 14 天。
回答by Pekka
Your main problem is that RAND()
doesn't allow a range of values like you specify. It will always return a value between 0 and 1.
您的主要问题是RAND()
不允许您指定的值范围。它将始终返回一个介于 0 和 1 之间的值。
I can't work out a 1..14 random solution right now, but to get you started, this will pick a random date within the last 10 days:
我现在无法制定 1..14 随机解决方案,但是为了让您开始,这将在过去 10 天内选择一个随机日期:
SET col = DATE(DATE_SUB(NOW(), INTERVAL ROUND(RAND(1)*10) DAY))