Home >Database >Mysql Tutorial >In MySQL, how to automatically insert date and time while inserting NULL values ​​into other columns?

In MySQL, how to automatically insert date and time while inserting NULL values ​​into other columns?

王林
王林forward
2023-08-29 11:09:071304browse

In MySQL, how to automatically insert date and time while inserting NULL values ​​into other columns?

In MySQL, we can automatically insert the current date and time into this column when NULL values ​​are inserted into other columns by declaring the column as DEFAULT CURRENT_TIMESTAMP. In this case, we cannot declare the column in which we want to insert NULL value NOT NULL.

mysql> Create Table Testing1(Name Varchar(20),
RegStudent TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
Query OK, 0 rows affected (0.15 sec)

The above query will create a table "Testing1" with one column named "Name" (not declared as "NOT NULL") and other columns named "RegDate" declared as DEFAULT CURRENT_TIMESTAMP. Now, when inserting a NULL value into the "name" column, the current date and time is automatically inserted into another column.

mysql> Insert into Testing1(Name) Values(NULL);
Query OK, 1 row affected (0.08 sec)

mysql> Insert into Testing1(Name) Values(NULL);
Query OK, 1 row affected (0.04 sec)

mysql> Select * from Testing1;
+------+---------------------+
| Name | RegStudent |
+------+---------------------+
| NULL | 2017-10-29 04:46:59 |
| NULL | 2017-10-29 04:47:02 |
+------+---------------------+
2 rows in set (0.05 sec)

From the above query, we can see that when inserting a NULL value in "Name", the date and time are also automatically inserted.

The above is the detailed content of In MySQL, how to automatically insert date and time while inserting NULL values ​​into other columns?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete