如何使用 MySQL 在过去 2 周内更新具有随机日期的列?
例如(代码实际上不起作用):
UPDATE mytable
SET col = sysdate() - rand(1, 14);
最佳答案
你可以用这个表达式得到一个随机整数:
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
使用它来生成随机的天数、小时数或分钟数(取决于分辨率)并将该数字添加到当前日期。
完整的表达式是:
-- 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 - 在 MySQL 中插入/更新随机日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4546111/