I would try an array of objects

[
 {name:'Hy Dag3', points:'55040464', rank:'master', hotStreak:114,...},
 {name:'Hkj', points:'554064', rank:'novice', hotStreak:14,...}
]

and then

this.conn.query("INSERT summoners SET ? " +
" ON DUPLICATE KEY UPDATE name = VALUES(name), rank = VALUES(rank)...

Because according to doc:

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function (error, results, fields) {
  if (error) throw error;
  // Neat!
});
console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
Answer from Gerardo Rosciano on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 67626972 › bulk-insert-on-duplicate-key-update-with-50-columns
javascript - bulk INSERT on DUPLICATE KEY UPDATE with 50+ columns - Stack Overflow
If not you can review this example: https://github.com/dusthaines/mysqljs_setup_snippet/blob/master/app.js ... Sign up to request clarification or add additional context in comments. ... If you need to either insert or update each of 500 rows, and there are 50 columns potentially inserted, then IODKU is likely to be a clear winner in speed.
Discussions

Syntax help for Bulk insert with ON DUPLICATE
I am having trouble with a bulk insert with a conditional update. Table looks like this: CREATE TABLE status(idint(11) NOT NULL,keynamevarchar(100) NOT NULL,val varchar(100) NOT NULL, PRIMARY KEY (id,keyname) ) I have been trying to put qStatus into an extra array ([qStatus] instead of qStatus) ... More on github.com
🌐 github.com
3
October 19, 2015
mysql - INSERT INTO .. ON DUPLICATE KEY UPDATE for multiple items - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
javascript - INSERT ON DUPLICATE KEY UPDATE with SUM or MINUS MySQL - Stack Overflow
I was searching real hard for an answer but couldn't find one I have this table and I am using this query to update it (this query is a must because I have dynamic inputs from my frontend so I can More on stackoverflow.com
🌐 stackoverflow.com
javascript - How to properly use ON DUPLICATE KEY UPDATE in Node.js MySQL - Stack Overflow
I'm using Node.js to push values to a MySQL table like: for (var i = 0; i More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
github.com › mysqljs › mysql › issues › 1248
Syntax help for Bulk insert with ON DUPLICATE · Issue #1248 · mysqljs/mysql
October 19, 2015 - qStatus = []; qStatus.push([33, 'a', 'a1']) qStatus.push([33, 'a', 'a2']) qStatus.push([33, 'b', 'a3']) //this works in mysql workbench INSERT INTO status(id, keyname, val) VALUES(3, "ut", "a4"), (3, "ut", "a5") ON DUPLICATE KEY UPDATE val = VALUES(val); var s = 'INSERT INTO status(id, keyname, val) VALUES(?) ON DUPLICATE KEY UPDATE val = VALUES(val)'; dbioCore.loggingpool.query(s, qStatus, function (err, res) { if (err) { logger.error("Failure bulk inserting status data" + err); } qStatus = []; //clear queue ·
Author   Laro88
Top answer
1 of 2
9

I'm going to short this to three columns, and assume id is the only unique column.

db.query("INSERT INTO movies (id, adult, backdrop_path) VALUES (?, ?, ?)
 ON DUPLICATE KEY UPDATE adult=VALUES(adult), backdrop_path=VALUES(backdrop_path)",
flattenedData, function (err, result) {
...

This means if the insert results in a duplicate on the primary/unique column (id), then copy the other columns from the values you tried to insert in the VALUES clause into their respective column, overriding what their value was previously in the existing row.

There's no shortcut for that; you have to spell out all such column assignments.

I'm pretty sure the argument to query() for parameters should be an array, but it looks like your flattenedData is already an array since you're pushing to it. So I don't think you need to put it in square-brackets.

2 of 2
0

I was confused by how to get this to work in a react/redux app and eventually came to the "correct" method.

My implementation required me to update one field value per record for an arbitrary number of records in a table with 21 fields.

If you are passing data as an array structure it like [['dataString',666.66],['dataString2',666666.66],['dataString3',666666666.66]] and then make sure you pass this whole thing as an array to the query function. See itemQtyData in my code sample below.

Another thing that tripped me up was the use of brackets around the values replacement string. I didn't need them. The examples I looked at showed implementations that needed them. I also only used a single ? for all the values. So instead of using (?,?) to represent the values in the query, which didn't work, I used ?.

I found it unnecessary to supply all the field names and the corresponding values for the table. MySQL will warn you if fields don't have a default value. I haven't found this to be an issue in this case.

You can console.log the formatted sql in SqlString.format function in the file node_modules/sqlstring/lib/SqlString.js. I found this useful to see exactly why the query wasn't working and to have something that I could plug into MySQL Workbench to mess around with.

Edit: You can also do this console.log(connection.query(yourQuery, [someData], callback)) and you get the sql and lot's more when the function executes. Might make more sense than adding console.log calls to the module code.

Hope this helps!

let itemQtyData = order.map(item => {
    return [
      `${item.id}`,
      `${Number(item.products_quantity - Number(item.quantity_to_add))}`
    ];
  });

const updateQtyQuery =`INSERT INTO products (products_id, products_quantity) VALUES ? ON DUPLICATE KEY UPDATE products_quantity=VALUES(products_quantity)`;

connectionOSC.query(
  updateQtyQuery,
  [itemQtyData],
  (error, results, fields) => {
    if (error) throw error;

    const response = {
      statusCode: 200,
      headers: {
        "Access-Control-Allow-Origin": "*"
      },
      body: saleId,
      response: results,
      isBase64Encoded: false
    };
context.succeed(response);
});
Find elsewhere
🌐
MariaDB
mariadb.com › kb › en › insert-on-duplicate-key-update
INSERT ON DUPLICATE KEY UPDATE | Server | MariaDB Documentation
Complete guide to inserting data in MariaDB. Complete INSERT syntax for single rows, bulk operations, and ON DUPLICATE KEY handling for production use.
🌐
Reddit
reddit.com › r/mysql › how to run insert query with on duplicate key update in a single batch
r/mysql on Reddit: How to run INSERT query with ON DUPLICATE KEY UPDATE in a single batch
January 18, 2020 -

Hello,

I want to insert multiple rows in a single query, which have ON DUPLICATE KEY UPDATE statements for each row.

I want to do this for performance reasons, I can achieve this by running all insert queries in a loop from application code, but that'll be too heavy.

MySQL => 5.7

Application code =>Python 3.6

🌐
Stack Exchange
dba.stackexchange.com › questions › 258914 › insert-on-duplicate-key-update-to-update-multiple-rows-in-single-query
mysql - INSERT ON DUPLICATE KEY UPDATE to UPDATE multiple rows in single query - Database Administrators Stack Exchange
February 4, 2020 - Reassigning the values of the fields which causes ODKU execution makes no sense except DO NOTHING emulation (but INSERT IGNORE is more simple in such case). ... You have two rows with id=2. If that is a typo, please fix it. If it is deliberate, please explain the intent. ... Thanks to #danblack and dbfiddle.uk in short I determined that I was missing one of the columns in the ON DUPLICATE KEY UPDATE.
🌐
Stack Overflow
stackoverflow.com › questions › 42818301 › bulk-inserting-rows-on-duplicate-key-update-into-mysql-through-node-js-while-als
Bulk inserting rows on duplicate key update into mysql through Node.js while also executing a mysql function - Stack Overflow
March 16, 2017 - But, in this case, the 'commit' column is a BINARY field, so I need to execute the MySQLUNHEX() on the commit string so it stores it properly in the database. Passing the module this SQL throws the Error: ER_PARSE_ERROR · INSERT INTO table1 (super_repo, reference, path, sub_repo, commit) VALUES (?, ?, ?, ?, UNHEX(?)) ON DUPLICATE KEY UPDATE sub_repo = VALUES(sub_repo), commit = VALUES(commit)
🌐
MySQL
forums.mysql.com › read.php
Bulk Insert On Duplicate Key Update Performance
July 9, 2007 - Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party
🌐
MySQL
dev.mysql.com › doc › refman › 8.0 › en › insert-on-duplicate.html
MySQL :: MySQL 8.0 Reference Manual :: 15.2.7.2 INSERT ... ON DUPLICATE KEY UPDATE Statement
January 13, 2022 - INSERT INTO t1 (a,b,c) VALUES (1,2,3),(4,5,6) AS new ON DUPLICATE KEY UPDATE c = new.a+new.b; If, in addition, you use the column aliases m, n, and p, you can omit the row alias in the assignment clause and write the same statement like this: INSERT INTO t1 (a,b,c) VALUES (1,2,3),(4,5,6) AS ...
🌐
GitHub
github.com › mysqljs › mysql › issues › 2251
Multi statement bulk insert · Issue #2251 · mysqljs/mysql
July 31, 2019 - connection.query(` BEGIN; INSERT INTO FAB_BCGH (OCNO, CUSTNAME, STYLENO, STYLDESC) VALUES (${mysql.escape(OC)}, ${mysql.escape(CustName)}, ${mysql.escape(StyleNo)}, ${mysql.escape(StyleDesc)}) on duplicate key update BCGUNIQ = LAST_INSERT_ID(BCGUNIQ); SELECT LAST_INSERT_ID() INTO @last_inserted_id_var_1; INSERT INTO FAB_BCGD(BCGUNIQ, ITEMCODE, ITEMDESC, TTLROLLGEN) VALUES (@last_inserted_id_var_1, ${mysql.escape(ItemNo)}, ${mysql.escape(ItemDesc)}, ${mysql.escape(tableData.length)}) on duplicate key update BCGLINE = LAST_INSERT_ID(BCGLINE), TTLROLLGEN = TTLROLLGEN + VALUES(TTLROLLGEN); SELECT
Author   redixhumayun
🌐
Prisma
prisma.io › dataguide › mysql › inserting-and-modifying-data › insert-on-duplicate-key-update
ON DUPLICATE KEY UPDATE to upsert and modify data in MySQL
MySQL's INSERT...ON DUPLICATE KEY UPDATE construct allows you to insert data while avoiding conflicts with existing records. Combined with the VALUES() function, you can use it to make contextual updates to records that already exist without ...
🌐
MySQL Tutorial
mysqltutorial.org › home › mysql basics › mysql insert on duplicate key update statement
MySQL INSERT ON DUPLICATE KEY UPDATE Statement
December 27, 2023 - Summary: in this tutorial, you will learn how to use MySQL INSERT ON DUPLICATE KEY UPDATE statement to insert data into a table or update data if a duplicate key violation error occurs.
🌐
TutorialsPoint
tutorialspoint.com › mysql › mysql-insert-on-duplicate-update.htm
MySQL − Insert on Duplicate Key Update
However, if we use the MySQL ON DUPLICATE KEY UPDATE clause with with the INSERT INTO statement, MySQL will update the existing rows with the new values instead of showing an error.
🌐
MySQL
dev.mysql.com › doc › refman › 8.4 › en › insert-on-duplicate.html
MySQL :: MySQL 8.4 Reference Manual :: 15.2.7.2 INSERT ... ON DUPLICATE KEY UPDATE Statement
INSERT INTO t1 (a,b,c) VALUES (1,2,3),(4,5,6) AS new ON DUPLICATE KEY UPDATE c = new.a+new.b; If, in addition, you use the column aliases m, n, and p, you can omit the row alias in the assignment clause and write the same statement like this: INSERT INTO t1 (a,b,c) VALUES (1,2,3),(4,5,6) AS ...