I am referencing the answer by Gunaseelan to this article. UPDATE if exists else INSERT in SQL
I was having a problem writing a query to update if exists else insert in MySQL, but Gunaseelan's solution worked great on the mysql command line. However when I try to use it in a bash script it breaks. I can't seem to see what's wrong here and could really use another pair of eyes to help me figure it out.
mysql> describe wordfreqs;
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| frequency | int(11) | NO | | NULL | |
| n_gram | varchar(100) | NO | UNI | NULL | |
| logic_number | int(11) | YES | | NULL | |
| s | tinyint(4) | YES | | NULL | |
| substitution | varchar(100) | YES | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
Data:
1,PACER ,,,
1,LIQUID NAILS,,,
1,F P C,,,
1,ACE ,,,
3,SIMPSON,,,
1,SUREBONDER,,,
1,DO IT BEST,,,
1,LIQUID NAILS,,,
1,JACKSON,,,
1,DURO,,,
15,JB,1,S,JB WELD
13,DEVIL,1,S,RED DEVIL
mysql> INSERT INTO wordfreqs (frequency, n_gram, logic_number, s, substitution) VALUES (1,'BUCKET',7,1,'BOUQUET') ON DUPLICATE KEY UPDATE frequency = frequency+10;
Query OK, 2 rows affected (0.04 sec)
mysql> SELECT * FROM wordfreqs; +----+-----------+--------+--------------+------+--------------+
| id | frequency | n_gram | logic_number | s | substitution |
+----+-----------+--------+--------------+------+--------------+
| 1 | 22 | BUCKET | 7 | 1 | BOUQUET |
+----+-----------+--------+--------------+------+--------------+
1 row in set (0.00 sec)
However in bash script I get different results...
mysql --login-path=local SKU_project -N -e "INSERT INTO wordfreqs (frequency, n_gram, logic_number, s, substitution) VALUES ($freq,'$Ngram',$logicNumber,'$S','$substitution') ON DUPLICATE KEY UPDATE frequency = frequency+$freq;"
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''','') ON DUPLICATE KEY UPDATE frequency = frequency+393' at line 1
Any help would be greatly appreciated. :-)
Thanks @ marekful. Here is the output from a couple of the echo statements:
INSERT INTO wordfreqs (frequency, n_gram, logic_number, s, substitution)
VALUES (1,'PACER ',,'','') ON DUPLICATE KEY UPDATE frequency = frequency+1;
INSERT INTO wordfreqs (frequency, n_gram, logic_number, s, substitution)
VALUES (15,'JB',S,'S','JB WELD') ON DUPLICATE KEY UPDATE frequency = frequency+15;
INSERT INTO wordfreqs (frequency, n_gram, logic_number, s, substitution) VALUES (13,'DEVIL',S,'S','RED DEVIL') ON DUPLICATE KEY UPDATE frequency = frequency+13;