我在mysql中有一个有效的查询,但是通过Jest测试,它给出了以下错误:
您的SQL语法有错误;检查与您的MariaDB服务器版本相对应的手册,以在
附近使用正确的语法
FROM(SELECT
f.user' at line 4
SELECT和f.user之间的空行是模板$ {querySubSelect}
但出于某种原因,杰斯特(Jest)不会阅读querySubSelect的参考。
因此查询应如下所示:
FROM (SELECT SUBSTRING(SUBSTRING(f.answers, 1, 2), 2) AS Answer1,
SUBSTRING(SUBSTRING(f.answers, 2, 3), 3) AS Answer2,
SUBSTRING(SUBSTRING(f.answers, 3, 4), 4) AS Answer3,
SUBSTRING(SUBSTRING(f.answers, 4, 5), 5) AS Answer4,
SUBSTRING(SUBSTRING(f.answers, 5, 6), 6) AS Answer5,
f.userid,....
我的完整查询是:
let querySelect = ``
for (var i = 1; i <= answersLength; i++) {
if (i == answersLength) {//last entry should be without ","
querySelect += `ROUND(AVG(Answer${i}), 1) AS avg${i} `
} else {
querySelect += `ROUND(AVG(Answer${i}), 1) AS avg${i}, `
}
}
//set yo the Sub select parameter for query
let querySubSelect = ``
for (var i = 1; i <= answersLength; i++) {
querySubSelect += `SUBSTRING(SUBSTRING(f.answers, ${i}, ${i + 1}), ${i + 1}) AS Answer${i},`
}
const counselorAvgAnswer = await UserModel.sequelize.query(`
SELECT
name, ${querySelect}
FROM
(SELECT
${querySubSelect}
f.userid AS clientid
FROM
user AS u, feedback AS f
WHERE
u.id = f.userid
AND u.role IN ('counsellor' , 'leader')) AS feedbackSubQuery,
user AS user
WHERE
clientid = user.id
GROUP BY clientid
ORDER BY name ASC`)
.then(e => { return e[0] })
查询在我的代码中工作得很好,但是运行Jest测试会破坏所有测试,并且出现与我相同的错误
答案 0 :(得分:0)
仍然不知道问题出在哪里,但我这样解决了: 通过切换查询标题/选择的顺序
let querySelect = ``
for (var i = 1; i <= answersLength; i++) {
querySelect += `ROUND(AVG(Answer${i}), 1) AS avg${i},`
}
//set yo the Sub select parameter for query
let querySubSelect = ``
for (var i = 1; i <= answersLength; i++) {
//the substring function is to take the acutal number from the array inside the string 'f.answers'
querySubSelect += `SUBSTRING(SUBSTRING(f.answers, ${i}, ${i + 1}), ${i + 1}) AS Answer${i},`
}
// }
const counselorAvgAnswer = await UserModel.sequelize.query(`
SELECT
${querySelect}
name
FROM
(SELECT
${querySubSelect}
f.userid AS clientid
FROM
user AS u, feedback AS f
WHERE
u.id = f.userid
AND u.role IN ('counsellor' , 'leader')) AS feedbackSubQuery,
user AS user
WHERE
clientid = user.id
GROUP BY clientid
ORDER BY name ASC`)
.then(e => { return e[0] })
.catch(function(err) {
console.log(err);
});
return counselorAvgAnswer