Home >Database >Mysql Tutorial >Detailed explanation of the definition and usage of MySQL timestamp
Detailed explanation of the definition and usage of MySQL timestamp
In MySQL, timestamp (timestamp) is a data type used to store date and time information. Timestamps are usually used to record the creation time or last update time of data to facilitate data tracking and management. The timestamp type in MySQL has an automatic update function, which can automatically record the current timestamp when inserting or updating data.
Definition of timestamp
In MySQL, the definition format of timestamp is TIMESTAMP
, which can have optional parameters, such as default values , automatic updates, etc. The data range of the timestamp is from 00:00:01 on January 1, 1970 to a certain time point in 2038, accurate to the second level. If a larger time range is required, the DATETIME
type can be used.
How to use timestamp
When creating a table, you can define a timestamp field and set its default value to the current time so that the current timestamp is automatically recorded when new data is inserted. An example is as follows:
CREATE TABLE example_table ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
In the above example, a table named example_table
is created, which contains a timestamp field named created_at
.
When inserting new data into the table, you do not need to specify the value of the timestamp field, MySQL will automatically use the current timestamp filling. The example is as follows:
INSERT INTO example_table (name) VALUES ('John');
In the above example, a record is inserted into the example_table
table,# The ##created_at field will be automatically populated with the current time.
ON UPDATE CURRENT_TIMESTAMP## for the timestamp field. #Attributes. The example is as follows: ALTER TABLE example_table MODIFY created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
In this way, when the data in theexample_table
table is updated, created_at
The field will be automatically updated to the current timestamp.
SELECT * FROM example_table WHERE created_at > '2022-01-01';
This query will return thecreated_at
field value in January 2022 Records after 1 day. To sum up, MySQL timestamp is a data type that is convenient for recording time information. Through appropriate definition and settings, the function of automatically generating and automatically updating timestamps can be realized. In practical applications, timestamps can help us better track data changes and operation times, and improve the efficiency and accuracy of data management.
The above is the detailed content of Detailed explanation of the definition and usage of MySQL timestamp. For more information, please follow other related articles on the PHP Chinese website!