Mysql 在给定的日期时间范围内插入随机日期时间 [英] Mysql insert random datetime in a given datetime range

查看:83
本文介绍了Mysql 在给定的日期时间范围内插入随机日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 SQL,我可以在给出范围的列中插入随机日期时间值吗?

With SQL , Can I insert random datetime values in a column giving a range?

例如,给定范围 2010-04-30 14:53:272012-04-30 14:53:27

For example, given a range of 2010-04-30 14:53:27 to 2012-04-30 14:53:27

我对范围部分感到困惑.因为我会这样做

I'm getting confused with the range part. as i will have just done this

INSERT INTO `sometable` VALUES (RND (DATETIME())) 

推荐答案

以下示例应该会有所帮助:

Here is an example that should help:

INSERT INTO `sometable` VALUES(
    FROM_UNIXTIME(
        UNIX_TIMESTAMP('2010-04-30 14:53:27') + FLOOR(0 + (RAND() * 63072000))
    )
)

它使用日期 2010-04-30 14:53:27 作为基础,将其转换为 Unix 时间戳,并将从 0 到 +2 年的随机秒数添加到基准日期并将其转换回 DATETIME.

It uses the date 2010-04-30 14:53:27 as the base, converts that to a Unix timestamp, and adds a random number of seconds from 0 to +2 years to the base date and converts it back to a DATETIME.

它应该非常接近,但在更长的时间段内闰年和其他调整会使其失效.

It should be pretty close but over longer time periods leap years and other adjustments will throw it off.

这篇关于Mysql 在给定的日期时间范围内插入随机日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆