随机化所有现有条目的日期时间列值

时间:2017-09-07 20:53:27

标签: mysql sql datetime

所以,我为刚刚构建的展示演示项目得到了这个虚拟表,所以我开始按顺序上传帖子,有没有办法修改或改变日期时间列,只需将其改为随机日期?

title    |  content   | date
title1   | xxxxxxxxx  | 2017-06-06 12:13:01 <- random generated date
title2   | xxxxxxxxx  | 2017-19-07 21:37:57 <- random generated date

所以...我想做的只是运行一个查询,以便日期列保持类似

$n_quantity

1 个答案:

答案 0 :(得分:1)

您需要有一个PRIMARY KEY(即id)才能使用自联接更新查询执行此操作。

如果没有,您可以使用title来匹配行,但这会导致所有具有相同标题的帖子以相同的随机日期结束:

/* convert date range to seconds to get an INT to express randomization range */
SET @min := UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2009 12:00AM', '%M %d %Y %h:%i%p'));
/* subtract the max ID from the range so we can add the ID later to the range 
 * without getting out of range values */
SET @max := UNIX_TIMESTAMP(STR_TO_DATE('Sep 08 2017 01:00AM', '%M %d %Y %h:%i%p')) - (SELECT MAX(id) FROM table);

/* join a second reference of the table as a source for the update */
UPDATE table AS target JOIN table AS source ON source.id = target.id
/* and add the source ID to the range to force the optimizer to calculate
 * a random number for each row independently */
SET target.date = FROM_UNIXTIME( ROUND((RAND()*(@max - @min + source.id))+@min) )
/* dont forget to link source and destination with the primary key! */
WHERE source.id = target.id