在Sequelize中使用@variables MySQL

时间:2019-05-17 17:25:50

标签: mysql node.js sequelize.js

我正尝试使用SET变量从MySQL(Sequelize Raw Query)中获取迭代器,如下所示:

SET @Variable:=0; SELECT @Variable:=@Variable+1 AS AddNewColumn

我的特定代码是:

SET @i = 0; SELECT @i:=@i+1 AS iterator, COUNT(ci.id) totalCases, ...

但是会引发以下错误:

'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 \'SELECT\n @i:=@i+1 AS iterator,\n COUNT(ci.id) totalCases,\n SUM(b_p.amount\' at line 2',

有什么主意吗?

顺便说一句,我正在使用MySQL 5.7:

mysql Ver 14.14 Distrib 5.7.26, for Linux (x86_64) using EditLine wrapper

2 个答案:

答案 0 :(得分:0)

已解决2019/05/17 14:12

在原始查询中,我在FROM中分配@rownum:= 0,在声明之前将其定位到表,如下所示:

FROM (SELECT @rownum:=0) case_imports, case_imports ci

在开始时:

SELECT (@rownum:=@rownum+1) AS id, COUNT(ci.id) totalCases,

最后,按ID排序:

ORDER BY id

答案 1 :(得分:0)

我发现您还可以通过将每个SQL语句(包括变量声明)分解为一个单独的查询来在Sequelize中使用变量:

await sequelize.query('SET @i = 0;');
const rows = await sequelize.query(
    'SELECT @i := @i + 1 AS iterator FROM someTable;',
    { type: sequelize.QueryTypes.SELECT },
);

或者如果您想使用交易:

await sequelize.transaction(async (transaction) => {
    await sequelize.query('SET @rank = -1;', { transaction });
    const querySql = `
        UPDATE someTable
            SET rank = (@rank := @rank + 1)
            WHERE groupId = :groupId
            ORDER BY totalPoints DESC, age ASC;`;
    await sequelize.query(querySql, {
        transaction,
        replacements: { groupId },
    });
});

此版本已在sequelize@4.44.3中进行了测试,我不确定在更高版本中是否会更改。