svratonzo
svratonzo

Reputation: 21

MySql insert with duplicate key

I have a DB called "csv_db" with a table called "reportinc".

The table has these columns:

ID incidente, Aperto da, Stato, Categoria, Area, Sottoarea, Titolo, Priorità, Data/ora apertura, Data/Ora risoluzione, Data/ora chiusura, Inizio Interruzione di servizio, Fine interruzione di servizio, Conteggio riassegnazioni, Gruppo di assegnazione, Assegnatario, Risolto da, Gruppo risoluzione, Chiuso da, Gruppo di chiusura, ID interazione, Id Remedy, Descrizione, Soluzione, Servizio Interessato, Servizi Interessati, CI interessato, CI operativo, Ultimo aggiornamento da

The primary and unique key is ID incidente

I need to import each day from .CSV (comma separated) and:

  1. Insert new rows with new value (ID incident also)
  2. Update existing rows in the list, if present.

I need to update rows if duplicate, and NOT append.

How to?

Upvotes: 2

Views: 126

Answers (1)

eggyal
eggyal

Reputation: 125865

As documented under LOAD DATA INFILE Syntax:

If you specify REPLACE, input rows replace existing rows. In other words, rows that have the same value for a primary key or unique index as an existing row. See Section 13.2.8, “REPLACE Syntax”.

Therefore:

LOAD DATA [LOCAL] INFILE '/path/to/csv'
    REPLACE
    INTO TABLE csv_db.reportinc
    [CHARACTER SET charset_name]
    FIELDS
        TERMINATED BY ','
        OPTIONALLY ENCLOSED BY '"'
    LINES
        TERMINATED BY '\r\n'
    [IGNORE 1 LINES]
    (`ID incidente`, `Aperto da`, `Stato`, `Categoria`, `Area`, `Sottoarea`,
     `Titolo`, `Priorità`, `Data/ora apertura`, `Data/Ora risoluzione`,
     `Data/ora chiusura`, `Inizio Interruzione di servizio`,
     `Fine interruzione di servizio`, `Conteggio riassegnazioni`,
     `Gruppo di assegnazione`, `Assegnatario`, `Risolto da`,
     `Gruppo risoluzione`, `Chiuso da`, `Gruppo di chiusura`,
     `ID interazione`, `Id Remedy`, `Descrizione`, `Soluzione`,
     `Servizio Interessato`, `Servizi Interessati`, `CI interessato`,
     `CI operativo`, `Ultimo aggiornamento da`)

Upvotes: 1

Related Questions