我正在尝试这样做,但似乎 MySQL 不允许我这样做。是否有解决此问题的方法,或者我是否希望始终在我的 INSERT 查询中包含该函数?
CREATE TABLE foo(
created INT NOT NULL DEFAULT UNIX_TIMESTAMP()
)
我知道接受 CURRENT_TIMESTAMP 默认值的 TIMESTAMP 类型,但我的客户坚持在数据库中使用纪元时间。
最佳答案
MySQL实现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 的建议并通过触发器设置它:
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)
关于mysql - 是否可以在 MySQL 中创建具有 UNIX_TIMESTAMP 默认值的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5331026/