gpt4 book ai didi

MySQL - insert into... on duplicate key update - 如何区分插入或更新?

转载 作者:行者123 更新时间:2023-11-29 05:01:45 24 4
gpt4 key购买 nike

我正在使用 Node.js。我使用 mysqlbluebird 包。

const pool = mysql.createPool({ ... });

const query = (stmt, params) => {
return Promise.promisify(pool.query, { context: pool })(stmt, params);
};

const params = { ... };

const stmt = 'insert into table set ? on duplicate key update ?';

return query(stmt, [params, params])
.then(results => {
// I want to know actually what is done, insert or update
});

最佳答案

返回对象中应该有一个键affectedRows。从引用中可以看出,affectedRows 插入时为 1,更新时为 0 或 2。

return query(stmt, [params, params])
.then(results => {
// I want to know actually what is done, insert or update
if (results.affectedRows === 1) {
// inserted
} else {
// updated
}
});

For INSERT ... ON DUPLICATE KEY UPDATE statements, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag, the affected-rows value is 1 (not 0) if an existing row is set to its current values.

引用:https://dev.mysql.com/doc/refman/8.0/en/mysql-affected-rows.html

关于MySQL - insert into... on duplicate key update - 如何区分插入或更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57457915/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com