![]() |
|
|||||||
![]() |
|
|
Thread Tools | Display Modes |
|
|
|
#1
IP: 112.87.30.158
|
|||
|
|||
|
Looking for a way to add random dates to a column in one of your MySQL tables?
I ran across this problem and found a straightforward solution. By utilizing str_to_date(), concat(), floor() and rand() you can specify a random date for a column. Code:
update mytable
set mycolumn = str_to_date(
concat(
floor(1 + rand() * (12-1)), /* Generate a random month */
'-',
floor(1 + rand() * (28 -1)), /* Generate a random day */
'-',
'2008'
),
'%m-%d-%Y'
);
|
|
#2
IP: 112.87.30.158
|
|||
|
|||
|
Here is a better way to do that:
Code:
UPDATE tablename SET datefield= ‘2005-01-01′ + interval rand()*883 This will fill in each rows datefield with a random date between 2005-01-01 and 2006-06-02. Hope that helps! |
|
#3
IP: 112.87.30.158
|
|||
|
|||
|
Here’s yet another way:
Code:
UPDATE tableName SET column = FROM_UNIXTIME(RAND() * (UNIX_TIMESTAMP(‘2015-7-20 15:00:00′) – UNIX_TIMESTAMP(‘2008-09-10 12:00:00′)) + UNIX_TIMESTAMP(‘2008-09-10 12:00:00′)); If you only have a DATE field, you can extract the date from the end result. For example: Code:
UPDATE tableName SET column = DATE(FROM_UNIXTIME(RAND() * (UNIX_TIMESTAMP(‘2015-7-20 15:00:00′) – UNIX_TIMESTAMP(‘2008-09-10 12:00:00′)) + UNIX_TIMESTAMP(‘2008-09-10 12:00:00′))); Good luck! |
![]() |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| MySQL毫秒值和日期的指定格式的相互转换 | Kaitlin | MySQL | 0 | 2015-04-18 11:01 PM |
| mysql 帮助文档使用 | Haddam | MySQL | 0 | 2014-11-26 06:43 PM |
| Simple Steps to Change Your Table Prefix in WordPress | Abby | WordPress | 0 | 2014-04-14 03:40 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 |