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()
)
I'm aware of the TIMESTAMP type that accepts a CURRENT_TIMESTAMP default, but my client insisted on using epoch time in the database.
From the documentation:
The way MySQL implements the
TIMESTAMP
data type, it is actually storing the epoch time in the database. So you could just use aTIMESTAMP
column with a default ofCURRENT_TIMESTAMP
and apply theUNIX_TIMESTAMP()
to it if you want to display it as an int: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:You can create triggers for this.
CREATE TRIGGER {trigger_name} BEFORE INSERT ON {table_name} FOR EACH ROW SET new.{field_name} = UNIX_TIMESTAMP(NOW());
CREATE TRIGGER my_trigger_name_1 BEFORE INSERT ON foo FOR EACH ROW SET new.created = UNIX_TIMESTAMP(NOW());
CREATE TRIGGER {trigger_name} BEFORE UPDATE ON {table_name} FOR EACH ROW SET new.{field_name} = UNIX_TIMESTAMP(NOW());
CREATE TRIGGER my_trigger_name_2 BEFORE UPDATE ON foo FOR EACH ROW SET new.created = UNIX_TIMESTAMP(NOW());
Well, if MySQL won't let you do it directly, you can always do it using a
BEFORE INSERT... FOR EACH ROW
trigger.