![]() |
|
|||||||
|
|
Thread Tools | Display Modes |
|
#1
IP: 112.87.30.158
|
|||
|
|||
|
Random date/time
Need to generate a random date in MySQL? Here: mysql> SELECT FROM_UNIXTIME(RAND() * 2147483647) AS `rand`; +---------------------+ | rand | +---------------------+ | 1998-04-01 21:42:48 | +---------------------+ 1 row in set (0.00 sec) Let's try once again and get a different random value: mysql> SELECT FROM_UNIXTIME(RAND() * 2147483647) AS `rand`; +---------------------+ | rand | +---------------------+ | 2028-03-21 22:44:43 | +---------------------+ 1 row in set (0.00 sec) OK, why 2147483647? Well, 2147483647 is the latest timestamp: mysql> SELECT FROM_UNIXTIME(2147483647) AS `rand`; +---------------------+ | rand | +---------------------+ | 2038-01-18 19:14:07 | +---------------------+ 1 row in set (0.00 sec) If you try one more second (2147483648), that's too much: mysql> SELECT FROM_UNIXTIME(2147483648) AS `rand`; +------+ | rand | +------+ | NULL | +------+ 1 row in set (0.01 sec) So RAND() gives you a random value between 0 and 1 and you multiply it with the largest value posible and this way you get a random date between 1969 and 2038. What if you want to generate random date in a defined period? A random date in 2009 Here goes: mysql> SELECT FROM_UNIXTIME(RAND() * (1262246400 - 1230796800) + 1230796800) AS `the_date`; +---------------------+ | the_date | +---------------------+ | 2009-04-27 05:01:04 | +---------------------+ 1 row in set (0.00 sec) And once again: mysql> SELECT FROM_UNIXTIME(RAND() * (1262246400 - 1230796800) + 1230796800) AS `the_date`; +---------------------+ | the_date | +---------------------+ | 2009-08-15 12:54:51 | +---------------------+ 1 row in set (0.01 sec) "What just happened?" When you want to limit the values in a range, say between start and end and you have a random value between 0 and 1 you'd need to subtract end - start which gives you the desired interval and then "move" the interval to the start (the beginning of the range). So the super-duper complicated formula is like: (end - start) * RAND + start And because you cannot possibly remember timestamps, UNIX_TIMESTAMP comes to the rescue: mysql> SELECT -> UNIX_TIMESTAMP('2009-01-01') AS start, -> UNIX_TIMESTAMP('2009-12-31') AS end; +------------+------------+ | start | end | +------------+------------+ | 1230796800 | 1262246400 | +------------+------------+ 1 row in set (0.00 sec) Thanks Thanks for reading! |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| MySQL Generate Random Date | Kensington | MySQL | 0 | 2015-04-18 11:02 PM |
| MySQL毫秒值和日期的指定格式的相互转换 | Kaitlin | MySQL | 0 | 2015-04-18 11:01 PM |
| mysql 帮助文档使用 | Haddam | MySQL | 0 | 2014-11-26 06:43 PM |
| mysql安装与简单使用 | sunshine | 服务器环境搭建 | 0 | 2006-01-11 07:29 PM |
| winxp下安装全新的apache,php(5.0),mysql(5.0)... | topvip | 服务器环境搭建 | 0 | 2006-01-08 10:28 PM |