Is it possible to create a column with a UNIX_TIMESTAMP default in MySQL?(是否可以在 MySQL 中创建一个具有 UNIX_TIMESTAMP 默认值的列?)
问题描述
我正在尝试这样做,但 MySQL 似乎不允许我这样做.是否有解决此问题的方法,还是希望我始终在 INSERT 查询中包含该函数?
I'm trying to do this, but it seems like MySQL isn't allowing me. Is there a solution to this issue or am I expected to always include the function in my INSERT queries?
CREATE TABLE foo(
created INT NOT NULL DEFAULT UNIX_TIMESTAMP()
)
我知道接受 CURRENT_TIMESTAMP 默认值的 TIMESTAMP 类型,但我的客户坚持在数据库中使用纪元时间.
I'm aware of the TIMESTAMP type that accepts a CURRENT_TIMESTAMP default, but my client insisted on using epoch time in the database.
推荐答案
MySQL 实现TIMESTAMP
数据类型的方式,实际上是在数据库中存储纪元时间.所以你可以只使用 TIMESTAMP
列的默认值 CURRENT_TIMESTAMP
并应用 UNIX_TIMESTAMP()
如果你想将它显示为内部:
The way MySQL implements the TIMESTAMP
data type, it is actually storing the epoch time in the database. So you could just use a TIMESTAMP
column with a default of CURRENT_TIMESTAMP
and apply the UNIX_TIMESTAMP()
to it if you want to display it as an int:
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 的建议并通过触发器进行设置:
However, if you really want the datatype of the column to be INT
, you can use R. Bemrose's suggestion and set it via trigger:
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 中创建一个具有 UNIX_TIMESTAMP 默认值的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是否可以在 MySQL 中创建一个具有 UNIX_TIMESTAMP 默认值的列?


基础教程推荐
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01