无法在 discordjs 中找到 mysql 语法错误

unable to find mysql syntax error in discordjs

我正在尝试使用 mysql 包在 discordjs 中进行 sql 查询。 查询(如果在 sql 服务器中使用)按预期完美运行, 但是我得到一个 PARSE ERROR 试图在 js 中使用相同的查询:

SET @ROW_NUMBER = 0; SELECT s.level,s.exp,s.number 
FROM ( SELECT userID,level,exp,(@ROW_NUMBER:=@ROW_NUMBER + 1 ) AS number FROM levels ORDER BY level DESC) AS s 
WHERE userID = "${userID}";

discordjs中的代码:

//some code...
con.query(`SET @ROW_NUMBER = 0; SELECT s.level,s.exp,s.number 
FROM ( SELECT userID,level,exp,(@ROW_NUMBER:=@ROW_NUMBER + 1 ) AS number 
FROM levels ORDER BY level DESC) AS s 
WHERE userID ="${userID}";`,(err,rows) =>{
 if(err)return console.log(err); 
//other code

我得到的错误:

code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use near 'SELECT s.level,s.exp,s.number FROM ( SELECT userID ,level ,exp ,(@ROW_NUMBER:...' at line 1",
sqlState: '42000',
index: 0,
sql: 'SET @ROW_NUMBER = 0; SELECT s.level,s.exp,s.number FROM ( SELECT
userID ,level ,exp ,(@ROW_NUMBER:=@ROW_NUMBER + 1 ) AS number FROM levels
ORDER BY level DESC) AS s WHERE userID = "258217948819357697";'

错误消息显示您的连接器不允许多查询(两个查询作为一批发送)。

将变量初始化移到 FROM 子句中。

SELECT s.level,s.exp,s.number 
FROM ( SELECT userID, level, exp, ( @ROW_NUMBER:=@ROW_NUMBER + 1 ) AS number 
       FROM levels, (SELECT @ROW_NUMBER := 0) init_variable
       ORDER BY level DESC ) AS s 
WHERE userID = "${userID}";

PS。如果您的 MariaDB 版本是 10.2.1 或更高版本,则在 CTE 中使用 ROW_NUMBER() window 函数而不是变量。