Insert/ Update random date in MySQL

2019-01-08 22:17发布

问题:

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);

回答1:

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;


回答2:

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.



回答3:

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))