【发布时间】:2022-01-31 13:42:46
【问题描述】:
我正在尝试编写一个 SQL 查询,如果它存在则更新一个条目,如果它不存在则插入一个新条目。 UPDATE ON DUPLICATE KEY 选项不起作用,因为我没有按主键查询。我所指的 SQL 语句在下面的 sql.query() 函数中。我还添加了错误消息。
Asset.create = (newAsset, result) => {
sql.query(
`if exists(SELECT * from asset WHERE
AssetId="${newAsset.AssetId}" AND
AccountID="${newAsset.AccountId}") BEGIN UPDATE asset set
Amount="${newAsset.Amount}" where AssetId="${newAsset.AssetId}"
AND AccountID="${newAsset.AccountId}" End else begin INSERT
INTO asset SET ? end`,
newAsset,
(err, res) => {
if (err) {
console.log("error", err);
result(err, null);
return;
}
result(null, { id: res.insertId, ...newAsset });
}
);
};
错误信息:
sqlMessage: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 'if exists(SELECT * from asset WHERE AssetId="bitcoin" AND AccountID="2c341fed-cf' at line 1,
【问题讨论】:
-
这样的构造只允许在函数和过程中,并且是不是有效的sql代码