Mysql insert random datetime in a given datetime range

前端 未结 8 1854
迷失自我
迷失自我 2020-11-29 04:59

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

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

相关标签:
8条回答
  • 2020-11-29 05:27

    This works perfectly even for leap years:

    select from_unixtime(
        unix_timestamp('2000-1-1') + floor(
            rand() * (
                unix_timestamp('2010-12-31') - unix_timestamp('2000-1-1') + 1
            )
        )
    )
    

    The idea is simple: Just take a random timestamp between the two timestamps, then convert it to a datetime using from_unixtime. This way you can ensure that each option has equal probability.

    0 讨论(0)
  • 2020-11-29 05:27

    Easiest way out:

    INSERT INTO `sometable` VALUES (SELECT timestamp('2010-04-30 14:53:27') - INTERVAL FLOOR( RAND( ) * 366) DAY);
    
    0 讨论(0)
  • 2020-11-29 05:27
    SET @MIN = '2019-06-29 00:53:27';
    SET @MAX = '2019-06-29 13:53:27';
    
    UPDATE tablename
    SET columnname = TIMESTAMPADD(SECOND, FLOOR(RAND() * TIMESTAMPDIFF(SECOND, @MIN, @MAX)), @MIN)
    WHERE `columnname` = condition
    
    0 讨论(0)
  • 2020-11-29 05:30

    This worked for me but my issue was a bit different. I had to assign certain values in a column to a random datetime.

        UPDATE Tablename
        SET columnName = addtime(concat_ws(' ','2018-07-25' + interval rand()*2 day 
        ,'00:00:00'),sec_to_time(floor(0 + (rand() * 86401))))
        WHERE columnName = condition;
    
    0 讨论(0)
  • 2020-11-29 05:33

    This should work nicely:

    SET @MIN = '2010-04-30 14:53:27';
    SET @MAX = '2012-04-30 14:53:27';
    SELECT TIMESTAMPADD(SECOND, FLOOR(RAND() * TIMESTAMPDIFF(SECOND, @MIN, @MAX)), @MIN);
    

    TIMESTAMPDIFF is used to determine the number of seconds in the date range. Multiply this by a random number between 0-1 results in a random number between 0 and the number of seconds in the range. Adding this random number of seconds to the lower bound of the range results in a random date between the data range bounds.

    0 讨论(0)
  • 2020-11-29 05:35

    Just try :

    SELECT TIMESTAMP('2012-04-30 14:53:27')-INTERVAL RAND()*365*2 DAY INTO tbl_name;
    
    0 讨论(0)
提交回复
热议问题