Insert/ Update random date in MySQL

2019-01-08 22:14发布

How would I update a column with a random date in the past 2 weeks using MySQL?

For example (code doesn't actually work):

UPDATE mytable
SET col = sysdate() - rand(1, 14);

3条回答
一纸荒年 Trace。
2楼-- · 2019-01-08 22:36

Your main problem is that RAND() doesn't allow a range of values like you specify. It will always return a value between 0 and 1.

I can't work out a 1..14 random solution right now, but to get you started, this will pick a random date within the last 10 days:

SET col = DATE(DATE_SUB(NOW(), INTERVAL ROUND(RAND(1)*10) DAY)) 
查看更多
孤傲高冷的网名
3楼-- · 2019-01-08 22:53
UPDATE mytable
SET col = CURRENT_TIMESTAMP - INTERVAL FLOOR(RAND() * 14) DAY

This sets col to a date between (and including) current date and current date - 13 days. Multiply by 15 to get current date - 14 days.

查看更多
不美不萌又怎样
4楼-- · 2019-01-08 22:54

You can get a random integer with this expression:

To obtain a random integer R in the range i <= R < j, use the expression FLOOR(i + RAND() * (j - i)). For example, to obtain a random integer in the range the range 7 <= R < 12, you could use the following statement:

SELECT FLOOR(7 + (RAND() * 5));

http://dev.mysql.com/doc/refman/5.1/en/mathematical-functions.html

Use that to generate a random number of days, hours or minutes (depending on the resolution) and add that number to current date. Full expression would be something like this:

SELECT NOW() - INTERVAL FLOOR(RAND() * 14) DAY;
查看更多
登录 后发表回答