dimanche 26 juillet 2015

SQLite3: On unique key duplicated, update a column

I've created a script which parses documents that contain urls and inserts them into a table. Here's the CREATE TABLE (SQLite3):

CREATE TABLE urls_parsed (id INTEGER PRIMARY KEY, 
url TEXT UNIQUE, 
times_mentioned INTEGER, 
insert_date DATE DEFAULT(datetime('now', 'localtime')))

I want to keep track of how many times the script tried to insert the same url into the table. That's why I declared "url" column UNIQUE and that's the purpose of the column "times_mentioned". Thus, if a URL is inserted for the first time:

  1. id automatically takes its corresponding value,
  2. url inserts the parsed url as it doesn't exist,
  3. times_mentioned inserts 1 (preferably by default, automatically, although that's not how it's working right now),
  4. insert_date inserts datetime now()

When a duplicated url is found, the insert should update the "times_mentioned" column by adding 1 to its current value (basically, a counter).

This is what I've tried:

INSERT INTO urls_parsed (id, url, times_mentioned) 
VALUES (NULL, "url.com", 1) 
ON DUPLICATE KEY UPDATE times_mentioned=times_mentioned+1;

but it's returning an error:

Query Error: near "ON": syntax error Unable to execute statement

How on earth can this be achieved? Thanks!

Aucun commentaire:

Enregistrer un commentaire