0%

MySQL随机取时间

随机生成日期、时间

用mysql自带函数生成随机日期/时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 取1224的随机整数,包括1224
SELECT FLOOR(12+(RAND()*13));

# 取0-24之间的随机数,不够2位的前补0
SELECT LPAD(FLOOR(0 + (RAND() * 23)),2,0);

# 给用户赋一个随机创建日期,年份为2015-2015
SELECT CONCAT(
FLOOR(2015 + ( RAND() * 1 )),
'-',
LPAD(FLOOR(10 + ( RAND() * 2 )),2,0 ),
'-',
LPAD(FLOOR(1 + ( RAND() * 25 )),2,0 )
);

# 给用户赋一个随机创建时间,年份为2019
SELECT CONCAT(
FLOOR(2019 + ( RAND() * 1 )),
'-',
LPAD(FLOOR(0 + ( RAND() * 12 )),2,0 ),
'-',
LPAD(FLOOR(1 + ( RAND() * 25 )),2,0 ),
' ',
LPAD(FLOOR(1 + ( RAND() * 23 )),2,0 ),
':',
LPAD(FLOOR(1 + ( RAND() * 59 )),2,0 ),
':',
LPAD(FLOOR(1 + ( RAND() * 59 )),2,0 )
);

函数说明

1
2
3
4
5
6
7
8
# 可以在01之间产生一个随机数:
RAND()

# 向下取整
FLOOR(x)

# 填充字符串左边
LPAD(str,len,padstr)