SQL Auto-Increment by DateTime

2020-03-06 07:20发布

问题:

Is there a way in my sql to auto increment by the date and time?

so say I have a table

                         mytable
 =====================================================
 = Comment_ID = First_Name =  Comment  =  DateTime   =
 =====================================================
 =     1     =      Bob   =  FooBar = 11-01-14 11:00 =
 =     2     =     Jack   =  Blah   = 11-01-14 12:29 =
 =     3     =     John   =  jonny  = 12-01-14 07:09 =
 =====================================================

Is there away to make the date auto-increment?

回答1:

Run this in your MySQL:

ALTER TABLE `mytable` 
CHANGE COLUMN `DateTime` `DateTime` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ;

This sets your default value to CURRENT_TIMESTAMP.



回答2:

You can set a default value for your datetime column, now(). This way whenever you add a row, it will automatically get current datetime.