很多时候我们在MySQL中存储时间,并不是直接存储成为date类型,或者是time类型的,而是存储一串数据,这个数据表示你存储的时间距离1970年1月1日00:00:00所隔的秒数,这个转换是通过数据库系统的转换时间的函数完成,所以无论我们是输入时间1980-1-2 12:3:30还是直接输入距离时间秒都是可以存储的时候都是用一串数字存储,时间格式的数据和数字之间就需要来回的转换
函数unix_timestamp()是将时间格式的数据转换成一个长整型的数据
函数from_unixtime()是将长整形的数据转换成为时间戳
时间转时间戳
create table test (dt datetime,dts bigint);
insert into test select now(),unix_timestamp(now());
select * from test;
时间戳转时间
create table test (dt datetime,dts bigint);
insert into test select now(),unix_timestamp(now());
select *,from_unixtime(dts) from test;
时间转字符串
select date_format(now(), ‘%Y-%m-%d’);
时间转时间戳
select unix_timestamp(now());
字符串转时间
select str_to_date(‘2016-01-02’, ‘%Y-%m-%d %H’);
字符串转时间戳
select unix_timestamp(‘2016-01-02’);
时间戳转字符串
select from_unixtime(1451997924,’%Y-%d’);
时间戳转时间
select from_unixtime(列名) from 表名;
时间戳字段进行统一的更新,如增加1天或减少1天,可使用timestampadd这个函数
update a set created = UNIX_TIMESTAMP(timestampadd(day, 1, from_unixtime(created)))
上面的sql语句就是把a表的created时间戳字段统一增加1天,减少1天填写-1即可
随机函数:rand()
select rand(),可以看到结果会是随机小数
取随机整数
方法1
A:select floor(rand()*N) —生成的数是这样的:12.0
B:select cast( floor(rand()*N) as int) —生成的数是这样的:12
方法2
A:select ceiling(rand() * N) —生成的数是这样的:12.0
B:select cast(ceiling(rand() * N) as int) —生成的数是这样的:12
其中里面的N是一个你指定的整数,如100,可以看出,两种方法的A方法是带有.0这个的小数的,而B方法就是真正的整数了。
区别:他们的生成随机数的范围:
方法1的数字范围:0至N-1之间,如cast( floor(rand()*100) as int)就会生成0至99之间任一整数
方法2的数字范围:1至N之间,如cast(ceiling(rand() * 100) as int)就会生成1至100之间任一整数