Background
I have a table with two columns, the one is the key, which is word and the other is not a key, and it's instances.
I want to insert each word to a new row, and increment it's instances field by 1.
Now, if the word that being inserted now is already exist, it should not be duplicated but it's instances filed should be incremented.
Example
instances by 1.instances by 1.instances by 1.So now the table will look like this:
hello 2
world 1
I have tried:
MySql_Connection.query("
INSERT INTO `my_database`.my_table
(`word`) VALUES ('"+ word_to_insert +"')
UPDATE `instances` = `instances` + 1
ON DUPLICATE KEY `instances` = `instances` + 1
");
getting a syntax error
Your statement should be
MySql_Connection.query("
INSERT INTO `my_database`.my_table
(`word`) VALUES ('"+ word_to_insert +"')
ON DUPLICATE KEY UPDATE `instances` = `instances` + 1
");
instead.
You should provide an DEFAULT value for your instances column too, to get the value of 1 in your instances column if inserting a new word.
CREATE TABLE my_table (
word VARCHAR(100) NOT NULL PRIMARY KEY,
instances INT NOT NULL DEFAULT 1
);