简体   繁体   English

在Knex.js中使用MYSQL SET @

[英]Using MYSQL SET @ in Knex.js

I have been looking through the docs and online but can not find an example or any information on this. 我一直在浏览文档和在线,但是找不到相关的示例或任何信息。

Can you use SET with Knex.js? 可以将SET与Knex.js一起使用吗? And if so, how? 如果是这样,怎么办? I want to create a ranked table, here is an example query from a tutorial. 我想创建一个排序表,这是教程中的示例查询。 But I can not get SET to work. 但是我不能让SET工作。

SET @rank=0;

SELECT @rank:=@rank+1 AS rank, fruit, amount
  FROM sales
 ORDER BY amount DESC

Barmar's response got me on the right path of ranking using Knex.js. Barmar的回应使我使用Knex.js进行了正确的排名。 Here is my final Knex.js statement for those that are looking. 这是我正在寻找的最终Knex.js语句。 I am able to create the table and list with it. 我能够创建表并使用它列出。

let schoolId = req.params.id;

knex.select(knex.raw('@rank:=@rank+1 AS rank'),'schools.SID',
knex.raw('ROUND(AVG(IF(reviews.active = 1,((Q1+Q2+Q3+Q4+Q5+Q6+Q7+Q8+Q9+Q10)/(10*10)*10), NULL)) ,1) AS average'))
.from('schools')
.joinRaw('CROSS JOIN (SELECT @rank := 0) AS vars')
.rightJoin('reviews', 'reviews.schoolID', 'schools.SID')
.where('schools.schoolCountry', '=', 'China')
.groupBy('schools.SID')
.orderByRaw('schools.SID DESC, schools.schoolCountryCode ASC ')
.then(function (rank) {
    console.log(rank);
    res.locals.ranking = rank;
    next();
}).catch(function (error) {
    console.log(error);
    res.send('An error occured');
});

It should work if knex.js keeps a database connection open between queries. 如果knex.js保持查询之间的数据库连接打开,它应该可以工作。 Variables only persist within a database connection, so if it opens a new connection for each query the variable will be lost between the SET and SELECT . 变量仅在数据库连接中保留,因此,如果它为每个查询打开一个新连接,则变量将在SETSELECT之间丢失。

But even if you can do it, a better way is to initialize the variable in the query itself: 但是,即使可以做到,更好的方法是在查询本身中初始化变量:

SELECT @rank := @rank + 1 AS rank, fruit, amount
FROM sales
CROSS JOIN (SELECT @rank := 0) AS vars
ORDER BY amount DESC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM