我正在尝试执行此操作,但是MySQL似乎不允许我这样做。是否有解决此问题的方法,或者我希望总是在我的INSERT查询中包括该函数?
CREATE TABLE foo( created INT NOT NULL DEFAULT UNIX_TIMESTAMP() )
我知道可以接受CURRENT_TIMESTAMP缺省值的TIMESTAMP类型,但是我的客户端坚持使用数据库中的纪元时间。
MySQL实现TIMESTAMP数据类型的方式,实际上是将纪元时间存储在数据库中。因此,如果您想将其显示为int,则可以使用TIMESTAMP默认值为的列CURRENT_TIMESTAMP并将其应用于该列UNIX_TIMESTAMP():
TIMESTAMP
CURRENT_TIMESTAMP
UNIX_TIMESTAMP()
CREATE TABLE foo( created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ); insert into foo values (current_Date()),(now()); select unix_timestamp(created) from foo; +-------------------------+ | unix_timestamp(created) | +-------------------------+ | 1300248000 | | 1300306959 | +-------------------------+ 2 rows in set (0.00 sec)
但是,如果您确实希望该列的数据类型为INT,则可以使用R. Bemrose的建议并通过触发器设置它:
INT
CREATE TABLE foo( created INT NULL ); delimiter $$ create trigger tr_b_ins_foo before insert on foo for each row begin if (new.created is null) then set new.created = unix_timestamp(); end if; end $$ delimiter ; insert into foo values (unix_timestamp(current_Date())), (null); select created from foo; +------------+ | created | +------------+ | 1300248000 | | 1300306995 | +------------+ 2 rows in set (0.00 sec)