Ricerca nel sito web

Implementazione di INSERT... ON DUPLICATE KEY UPDATE in MySQL


Quando si inserisce una nuova riga in una tabella, se la riga causa un duplicato nell'indice UNIQUE o nella CHIAVE PRIMARIA, è previsto un errore. Per risolvere questo problema, utilizzare AGGIORNAMENTO CHIAVE DUPLICATA. Usandolo nell'istruzione INSERT, la riga esistente verrà aggiornata con i nuovi valori.

Creiamo innanzitutto una tabella:

mysql> create table DemoTable
   -> (
   -> Value int
   -> );
Query OK, 0 rows affected (0.61 sec)

Ecco la query per creare un indice:

mysql> create unique index value_index on DemoTable(Value);
Query OK, 0 rows affected (0.77 sec)
Records: 0 Duplicates: 0 Warnings: 0

Inserisci alcuni record nella tabella utilizzando il comando di inserimento:

mysql> insert into DemoTable values(40) on duplicate key update Value=Value+1000;
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(50) on duplicate key update Value=Value+1000;
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(40) on duplicate key update Value=Value+1000;
Query OK, 2 rows affected (0.15 sec)

Visualizza tutti i record dalla tabella utilizzando l'istruzione select :

mysql> select *from DemoTable;

Ciò produrrà il seguente output:

+-------+
| Value |
+-------+
|    50 |
|  1040 |
+-------+
2 rows in set (0.00 sec)

Articoli correlati: