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

时间:2017-10-03 12:16:06

标签: mysql sql node.js parsing parse-error

我已经搜索了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               扔错了; //重新抛出非MySQL错误               ^        错误:ER_PARSE_ERROR:您的SQL语法中有错误;       检查与您的MySQL服务器版本相对应的手册,以便使用“#NOT NOT EXISTS”附近使用的正确语法(SELECT MarketName FROM   Skins WHERE MarketName =' Nova |李的月亮'在第1行               在Query.Sequence._packetToError(/var/www/html/bot/node_modules/mysql/lib/protocol/sequences/Sequence.js:52:14)               在Query.ErrorPacket(/var/www/html/bot/node_modules/mysql/lib/protocol/sequences/Query.js:77:18)               在Protocol._parsePacket(/var/www/html/bot/node_modules/mysql/lib/protocol/Protocol.js:279:23)               在Parser.write(/var/www/html/bot/node_modules/mysql/lib/protocol/Parser.js:76:12)               在Protocol.write(/var/www/html/bot/node_modules/mysql/lib/protocol/Protocol.js:39:16)               在Socket。 (/var/www/html/bot/node_modules/mysql/lib/Connection.js:103:28)               在emitOne(events.js:115:13)               在Socket.emit(events.js:210:7)               在addChunk(_stream_readable.js:266:12)               在readableAddChunk(_stream_readable.js:253:11)               --------------------               在Protocol._enqueue(/var/www/html/bot/node_modules/mysql/lib/protocol/Protocol.js:145:48)               在Connection.query(/var/www/html/bot/node_modules/mysql/lib/Connection.js:208:25)               在Request._callback(/var/www/html/bot/index.js:531:16)               在Request.self.callback(/var/www/html/bot/node_modules/request/request.js:186:22)               在emitTwo(events.js:125:13)               在Request.emit(events.js:213:7)               在请求。 (/var/www/html/bot/node_modules/request/request.js:1163:10)               在emitOne(events.js:115:13)               在Request.emit(events.js:210:7)               在IncomingMessage。 (/var/www/html/bot/node_modules/request/request.js:1085:12)

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

MySQL只允许编程块中的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