gpt4 book ai didi

mysql - 我只是找不到这个 MySQL "Exists()"错误的合适解决方案

转载 作者:行者123 更新时间:2023-11-29 10:35:12 25 4
gpt4 key购买 nike

我已经在 stackoverflow 上搜索了大约一个小时,但没有解决方案可以解决我的问题。

我想运行这段代码:

for (var skin in body){
connection.query(`IF NOT EXISTS(SELECT MarketName FROM Skins WHERE MarketName = ?);
THEN
INSERT INTO Skins (MarketName) VALUES (?);
END IF;`,[skin, skin]); }

但是如果我用nodejs运行它,我会得到这个错误:

/var/www/html/bot/node_modules/mysql/lib/protocol/Parser.js:80 throw err; // Rethrow non-MySQL errors ^ Error: ER_PARSE_ERROR: 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 NOT EXISTS(SELECT MarketName FROM Skins WHERE MarketName = 'Nova | Moon in Li' at line 1 at Query.Sequence._packetToError (/var/www/html/bot/node_modules/mysql/lib/protocol/sequences/Sequence.js:52:14) at Query.ErrorPacket (/var/www/html/bot/node_modules/mysql/lib/protocol/sequences/Query.js:77:18) at Protocol._parsePacket (/var/www/html/bot/node_modules/mysql/lib/protocol/Protocol.js:279:23) at Parser.write (/var/www/html/bot/node_modules/mysql/lib/protocol/Parser.js:76:12) at Protocol.write (/var/www/html/bot/node_modules/mysql/lib/protocol/Protocol.js:39:16) at Socket. (/var/www/html/bot/node_modules/mysql/lib/Connection.js:103:28) at emitOne (events.js:115:13) at Socket.emit (events.js:210:7) at addChunk (_stream_readable.js:266:12) at readableAddChunk (_stream_readable.js:253:11) -------------------- at Protocol._enqueue (/var/www/html/bot/node_modules/mysql/lib/protocol/Protocol.js:145:48) at Connection.query (/var/www/html/bot/node_modules/mysql/lib/Connection.js:208:25) at Request._callback (/var/www/html/bot/index.js:531:16) at Request.self.callback (/var/www/html/bot/node_modules/request/request.js:186:22) at emitTwo (events.js:125:13) at Request.emit (events.js:213:7) at Request. (/var/www/html/bot/node_modules/request/request.js:1163:10) at emitOne (events.js:115:13) at Request.emit (events.js:210:7) at IncomingMessage. (/var/www/html/bot/node_modules/request/request.js:1085:12)

非常感谢您的帮助。

最佳答案

MySQL 只允许在编程 block 中使用 IF 语句——存储过程、触发器等。

执行您想要的操作的正确方法是在 Skins(MarketName) 上创建唯一索引或约束。这样,数据库就能确保数据的完整性。您可以这样做:

create unique index unq_skins_marketname on Skins(MarketName);

然后,尝试插入重复项将导致错误。您通常可以通过执行以下操作来避免这种情况:

insert into skins(marketname)
values (?)
on duplicate key marketname = values(marketname); -- this is a no-op

关于mysql - 我只是找不到这个 MySQL "Exists()"错误的合适解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46544406/

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