¿Establecer NOW() como Valor Predeterminado para datetime datatype?


Tengo dos columnas en los usuarios de la tabla, a saber, registerDate and lastVisitDate que consisten en el tipo de datos datetime. Me gustaría hacer lo siguiente.

  1. Establecer el valor predeterminado de registerDate en MySQL NOW()
  2. Establezca el valor predeterminado de lastVisitDate en 0000-00-00 00:00:00 En lugar de null que utiliza por defecto.

Debido a que la tabla ya existe y tiene registros existentes, me gustaría usar Modificar tabla. He intentado usar las dos piezas de código a continuación, pero ninguna funciona.

ALTER TABLE users MODIFY registerDate datetime DEFAULT NOW()
ALTER TABLE users MODIFY registerDate datetime DEFAULT CURRENT_TIMESTAMP;

Me da error : ERROR 1067 (42000): Invalid default value for 'registerDate'

¿Es posible para mí establecer el valor de datetime predeterminado en NOW() en MySQL?

Author: ryanyuyu, 2011-04-28

12 answers

A partir de MySQL 5.6.5, puede usar el tipo DATETIME con un valor dinámico predeterminado:

CREATE TABLE foo (
    creation_time      DATETIME DEFAULT   CURRENT_TIMESTAMP,
    modification_time  DATETIME ON UPDATE CURRENT_TIMESTAMP
)

O incluso combinar ambas reglas:

modification_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Reference:
http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html

Antes de la versión 5.6.5, debe usar el tipo de datos TIMESTAMP, que se actualiza automáticamente cada vez que se modifica el registro. Desafortunadamente, sin embargo, solo puede existir un campo TIMESTAMP actualizado automáticamente por tabla.

CREATE TABLE mytable (
  mydate TIMESTAMP
)

Véase: http://dev.mysql.com/doc/refman/5.1/en/create-table.html

Si desea evitar que MySQL actualice el valor de la marca de tiempo en UPDATE (para que solo se active en INSERT), puede cambiar la definición a:

CREATE TABLE mytable (
  mydate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
 210
Author: Johan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-08 04:34:27

Uso un disparador como solución alternativa para establecer un campo datetime en NOW() para nuevas inserciones:

CREATE TRIGGER `triggername` BEFORE INSERT ON  `tablename` 
FOR EACH ROW 
SET NEW.datetimefield = NOW()

También debería funcionar para las actualizaciones

Las respuestas de Johan & Leonardo implican convertir a un campo de marca de tiempo. Aunque esto probablemente esté bien para el caso de uso presentado en la pregunta (almacenamiento de RegisterDate y LastVisitDate), no es una solución universal. Ver datetime vs timestamp pregunta.

 69
Author: wardk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:09:56

Mi solución

ALTER TABLE `table_name` MODIFY COLUMN `column_name` TIMESTAMP NOT
NULL DEFAULT CURRENT_TIMESTAMP;
 44
Author: Leonardo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-25 00:11:54

¡EUREKA !!!


Para todos aquellos que perdieron el corazón tratando de establecer un valor de DATETIME predeterminado en MySQL, sé exactamente cómo se siente/sintió. Así que aquí está:

`ALTER TABLE  `table_name` CHANGE `column_name` DATETIME NOT NULL DEFAULT 0

Observe cuidadosamente que No he agregado comillas simples/comillas dobles alrededor del 0.


Actualización Importante:

Esta respuesta fue publicada hace mucho tiempo. En ese entonces, funcionó en mi (probablemente más reciente) instalación de MySQL y me sentí con ganas de compartirlo. Por favor lea los comentarios a continuación antes de decidir utilizar esta solución ahora.

 12
Author: Augiwan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-17 13:17:48

Los documentos de Mysql 5.6 dicen que CURRENT_TIMESTAMP se puede usar como predeterminado para los tipos de datos TIMESTAMP y DATETIME:

Http://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html

 4
Author: Jean Rajotte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-09 12:52:01

La mejor manera es hacer un disparador:

/************ ROLE ************/
drop table if exists `role`;
create table `role` (
    `id_role` bigint(20) unsigned not null auto_increment,
    `date_created` datetime,
    `date_deleted` datetime,
    `name` varchar(35) not null,
    `description` text,
    primary key (`id_role`)
) comment='';

drop trigger if exists `role_date_created`;
create trigger `role_date_created` before insert
    on `role`
    for each row 
    set new.`date_created` = now();
 1
Author: Lucas Moyano Angelini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-27 02:52:41

En las versiones de mysql 5.6.5 y posteriores, puede utilizar datetimes precisos y establecer valores predeterminados también. Sin embargo, hay un poco sutil, que es pasar el valor de precisión tanto a la llamada a la función datetime como a la función NOW ().

Este Ejemplo Funciona:

    ALTER TABLE my_table MODIFY created datetime(6) NOT NULL DEFAULT NOW(6);

Este Ejemplo No Funciona:

    ALTER TABLE my_table MODIFY created datetime(6) NOT NULL DEFAULT NOW();
 1
Author: Matteius,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-06 22:36:12
`ALTER TABLE  `table_name` CHANGE `column_name` 
    timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP 
    ON UPDATE CURRENT_TIMESTAMP

Se puede utilizar para actualizar la marca de tiempo en la actualización.

 0
Author: veelen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-27 02:54:53

Esto funcionó para mí, usando MySQL:

ALTER TABLE `table_name` MODIFY `column_name` datetime NOT NULL DEFAULT NOW();
 0
Author: rosshump,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-02 09:06:17
ALTER TABLE table_name
  CHANGE COLUMN date_column_name date_column_name DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

Finalmente, Esto funcionó para mí!

 0
Author: Eagle_Eye,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-26 21:39:45

No estoy seguro de si esto sigue activo, pero aquí va.

En cuanto a establecer los valores predeterminados en Now(), no veo que sea posible para el tipo de datos DATETIME. Si desea utilizar ese tipo de datos, establezca la fecha de realizar la inserción como esto:

INSERT INTO Yourtable (Field1, YourDateField) VALUES('val1', (select now()))

Mi versión de MySQL es 5.5

 -1
Author: George,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-26 00:23:06

Esto funcionó para mí - acabo de cambiar INSERT a UPDATE para mi tabla.

INSERT INTO Yourtable (Field1, YourDateField) VALUES('val1', (select now()))
 -1
Author: Diiferent Generation,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-28 19:31:16