5

I'm trying to do an insert that if the id already exists it updates the row instead, but I can't seem to get it to work.

This is an abridged version of the insert since there are about 1400 rows that could be inserted/updated. The majority of the time the statement will act as a multi-row UPDATE that will run daily through a CRON job. It is supposed to update existing rows, but if I new item is added will INSERT it into the database.

INSERT INTO `buoy_stations` (`id`, `coords`, `name`, `owner`, `pgm`, `met`, `currents`)
VALUES 
('00922', Point(30,-90),'name 1','owner 1','pgm 1','y','y'),
('00923', Point(30,-90),'name 2','owner 2','pgm 2','y','y'),
('00924', Point(30,-90),'name 3','owner 3','pgm 3','y','y'),
('00925', Point(30,-90),'name 4','owner 4','pgm 4','y','y'),
('00926', Point(30,-90),'name 5','owner 5','pgm 5','y','y')
ON DUPLICATE KEY
UPDATE coords=coords, name=name, owner=owner, pgm=pgm, met=met, currents=currents;

What am I doing wrong that this doesn't work? It appears it must be in the UPDATE section based on the error.

#1064 - 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 'pgm=pgm, met=met, currents=currents'

I've read through the docs, and looked through several StackOverflow answers, but they seem to reflect the same kind of setup to the statement.

mtpultz
  • 17,267
  • 22
  • 122
  • 201
  • I dont see you updating anything? You are only adding the values that are already there? How would anything be updated like that? Might this cause the issue? – jonasfh Feb 04 '18 at 22:02
  • What is your primary or unique key? – Shadow Feb 04 '18 at 22:03
  • 1
    From your error message, you need a comma between `owner=owner` and `pgm=pgm`. – Sablefoste Feb 04 '18 at 22:07
  • `name` is a reserved keyword: https://dev.mysql.com/doc/refman/5.7/en/keywords.html#keywords-5-7-detailed-N. Try addind the `'` around it. – Sablefoste Feb 04 '18 at 22:12
  • @Sablefoste yep that's definitely an issue thanks now it runs the query but doesn't update the fields, which I think might be solved since I didn't use `values()` – mtpultz Feb 04 '18 at 22:12

1 Answers1

21

you forgot the values() key word

INSERT INTO `buoy_stations` (`id`, `coords`, `name`, `owner`, `pgm`, `met`, `currents`)
VALUES 
('00922', 'Point(30,-90)','name 1','owner 1','pgm 1','y','y'),
('00923', 'Point(30,-90)','name 2','owner 2','pgm 2','y','y'),
('00924', 'Point(30,-90)','name 3','owner 3','pgm 3','y','y'),
('00925', 'Point(30,-90)','name 4','owner 4','pgm 4','y','y'),
('00926', 'Point(30,-90)','name 5','owner 5','pgm 5','y','y')
ON DUPLICATE KEY
        UPDATE coords=values(coords), name=values(name), owner=values(owner), pgm=values(pgm), met=values(met), currents=values(currents);
guigoz
  • 674
  • 4
  • 21