
MySQL 随机日期/时间生成
- 生成24小时内时间:有微秒值
sql
mysql> select sec_to_time(rand() * 86400);
+-----------------------------+
| sec_to_time(rand() * 86400) |
+-----------------------------+
| 21:56:22.705685 |
+-----------------------------+
1 row in set (0.00 sec)
2.生成一天内随机时间
sql
mysql> select sec_to_time(floor(rand() * 86400));
+------------------------------------+
| sec_to_time(floor(rand() * 86400)) |
+------------------------------------+
| 08:44:18 |
+------------------------------------+
1 row in set (0.00 sec)
3.生成1小时内时间:包括微秒
sql
mysql> select sec_to_time(rand() * 3600);
+----------------------------+
| sec_to_time(rand() * 3600) |
+----------------------------+
| 00:04:40.939843 |
+----------------------------+
1 row in set (0.00 sec)
4.生成比当前时间小的90天内的随机日期:精确到天,注意负号 -90
sql
mysql> SELECT date_add(current_date, interval rand() * -90 day) rand_date;
+------------+
| rand_date |
+------------+
| 2023-10-14 |
+------------+
1 row in set (0.00 sec)
5.生成比当前时间大的90天内的随机日期:精确到天
sql
mysql> SELECT date_add(current_date, interval rand() * 90 day) rand_date;
+------------+
| rand_date |
+------------+
| 2023-12-03 |
+------------+
1 row in set (0.00 sec)
6.生成比当前时间小的90天内的随机时间:显示到秒实际精确到天
sql
mysql> SELECT date_add(NOW(), interval rand() * -90 day) rand_date;
+---------------------+
| rand_date |
+---------------------+
| 2023-10-07 11:06:14 |
+---------------------+
1 row in set (0.00 sec)
7.生成比当前时间小的90天内的随机时间:精确到微秒 90*24*3600 = 7776000 ,90天的总秒数。
sql
mysql> SELECT date_add(current_timestamp, interval rand() * -7776000 second);
+----------------------------------------------------------------+
| date_add(current_timestamp, interval rand() * -7776000 second) |
+----------------------------------------------------------------+
| 2023-10-27 23:40:25.021294 |
+----------------------------------------------------------------+
1 row in set (0.00 sec)
8.生成比当前时间小的90天内的随机时间:精确到秒,格式化
sql
mysql> SELECT DATE_FORMAT(date_add(current_timestamp, interval rand() * -7776000 second),'%Y-%m-%d %H:%i:%s');
+-------------------------------------------------------------------------------------------------+
| DATE_FORMAT(date_add(current_timestamp, interval rand() * -7776000 second),'%Y-%m-%d %H:%i:%s') |
+-------------------------------------------------------------------------------------------------+
| 2023-09-17 12:52:17 |
+-------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
--方法2:
select concat(date_add(current_date(),interval rand()*-90 day),' ',sec_to_time(floor(rand()*86400)))
总结:是用date_add()或者date_sub()方法,结合rand()方法进行随机谁的取值,从而实现随机取时间
参考:
1、https://blog.csdn.net/qq_39065491/article/details/134328488