Mysql
 SQL >> Database >  >> RDS >> Mysql

Risolvere l'errore MySQL ERROR 1067 con due colonne CURRENT_TIMESTAMP

Nelle versioni più vecchie di MySQL, una tabella può avere solo una colonna timestamp che ha come predefinito CURRENT_TIMESTAMP o NOW(): è un limite storico ben noto.

Per aggirarlo, assegna alla tua colonna created un predefinito timestamp ordinario e valido, e imposta il valore effettivo nel codice CRUD della tua applicazione. Poi riserva NOW() o CURRENT_TIMESTAMP come predefinito per la colonna updated.

Materiale di riferimento: https://dev.mysql.com/doc/refman/5.1/en/timestamp.html

Per illustrare ulteriormente il limite, considera questo tentativo di workaround basato su trigger:

CREATE TABLE testing_timestamps ( id INT NOT NULL AUTO_INCREMENT, pk_id INT NOT NULL, col1 TIMESTAMP DEFAULT 0, col2 TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY(id) ); delimiter $$ CREATE TRIGGER testing_timestamps_trigger AFTER INSERT ON testing_timestamps FOR EACH ROW BEGIN UPDATE testing_timestamps SET col1 = NOW() WHERE id = MAX(id); END; $$ delimiter ; INSERT INTO testing_timestamps (id) VALUES (0); 

L'output invece produce un errore:

mysql> INSERT INTO testing_timestamps (id) VALUES (0); ERROR 1442 (HY000): Can't update table 'testing_timestamps' in stored function/trigger because it is already used by statement which invoked this stored function/trigger. 

È un peccato, perché altrimenti un trigger sarebbe una soluzione elegante qui. Nota che MySQL 5.6.5 e successivi hanno attenuato il vincolo originario del singolo timestamp, quindi questo riguarda principalmente i server più vecchi.