MySQL:插入随机日期值取决于某些其他日期属性

时间:2013-11-25 09:29:26

标签: mysql database date datetime

在mysql db中的表X中,我想在新的空列中为每个具有1/01/1990之前出生日期的行插入随机周年日。请帮我解决,因为我是MySQL的新手

1 个答案:

答案 0 :(得分:0)

你可以使用RAND()生成一个范围内的随机整数(假设在23到75之间),就像这样

SELECT FLOOR(23 + RAND() * (75 - 23))

您填写表格的anniversary列的更新语句可能看起来像

UPDATE person 
   SET anniversary = dob + INTERVAL FLOOR(23 + RAND() * (75 - 23)) YEAR
 WHERE dob < '1990-01-01'

让我们做一个快速测试

mysql> CREATE TABLE person 
    -> (
    ->   id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    ->   name varchar(32) ,
    ->   dob DATE ,
    ->   anniversary DATE
    -> );
Query OK, 0 rows affected (0.02 sec)

mysql> INSERT INTO person (name, dob)
    -> VALUES
    -> ('John',   '1972-01-15'),
    -> ('Phil',   '1964-05-23'),
    -> ('Mark',   '1948-12-10'),
    -> ('Steven', '1991-02-28'),
    -> ('Helen',  '1987-07-01');
Query OK, 5 rows affected (0.00 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> UPDATE person 
    ->    SET anniversary = dob + INTERVAL FLOOR(23 + RAND() * (75 - 23)) YEAR
    ->  WHERE dob  SELECT * FROM person;
+----+--------+------------+-------------+
| id | name   | dob        | anniversary |
+----+--------+------------+-------------+
|  1 | John   | 1972-01-15 | 1999-01-15  |
|  2 | Phil   | 1964-05-23 | 2022-05-23  |
|  3 | Mark   | 1948-12-10 | 1979-12-10  |
|  4 | Steven | 1991-02-28 | NULL        |
|  5 | Helen  | 1987-07-01 | 2050-07-01  |
+----+--------+------------+-------------+
5 rows in set (0.00 sec)