问题描述
如何使用 MySQL 在过去 2 周内使用随机日期更新列?
How would I update a column with a random date in the past 2 weeks using MySQL?
例如(代码实际上不起作用):
For example (code doesn't actually work):
UPDATE mytable
SET col = sysdate() - rand(1, 14);
推荐答案
你可以用这个表达式得到一个随机整数:
You can get a random integer with this expression:
获得一个随机整数R范围 i <= R FLOOR(i + RAND() * (j - i))
.为了例如,要获得一个随机整数范围 范围 7 <= R <12、你可以使用以下语句:
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));
https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_rand
使用它来生成一个随机的天数、小时数或分钟数(取决于分辨率)并将该数字添加到当前日期.
Use that to generate a random number of days, hours or minutes (depending on the resolution) and add that number to current date.
完整表达式为:
-- Date only
SELECT CURRENT_DATE - INTERVAL FLOOR(RAND() * 14) DAY;
-- Date and time
SELECT CURRENT_TIMESTAMP - INTERVAL FLOOR(RAND() * 14 * 24 * 60 *60) SECOND;
演示
这篇关于在 MySQL 中插入/更新随机日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!