Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Insert/Update Multiple Rows Using ON DUPLICATE KEY [duplicate]

Tags:

mysql

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.

like image 456
mtpultz Avatar asked Feb 04 '18 21:02

mtpultz


Video Answer


1 Answers

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);
like image 69
guigoz Avatar answered Oct 30 '22 03:10

guigoz