Knex: 使用 knex 的另一个实例的“from”子句中的子查询

创建于 2014-10-22  ·  3评论  ·  资料来源: knex/knex

你好!
我有这个查询:

var scores = Bookshelf.knex('audition_vote').sum('voting_power as score').groupBy('audition_id')

我想包装这个查询,如:

var topScores = Bookshelf.knex.distinct('score').from(function() {
  // This works but i want to use "scores" variable
  this.sum('voting_power as score').from('audition_vote').groupBy('audition_id').as('scores'); 
});

console.log(topScores.toString()) 打印

select distinct `score` from (select sum(`voting_power`) as `score` from `audition_vote` group by `audition_id`) as `scores

如何在 from() 中使用变量“scores”????

question

最有用的评论

哦,你可以这样做:

var scores = Bookshelf.knex('audition_vote')
   .sum('voting_power as score')
   .groupBy('audition_id')
   .as('scores');
var topScores = Bookshelf.knex.distinct('score').from(scores.clone());

.as被忽略,除非它在子查询中,并且只有在其他地方改变scores查询时才需要克隆。

或者你可以这样做:

var scores = Bookshelf.knex('audition_vote')
   .sum('voting_power as score')
   .groupBy('audition_id');
var topScores = Bookshelf.knex.distinct('score').from(scores.clone().as('scores'));

所有3条评论

您最终要生成的查询是什么?

最后一个:

select distinct `score` from (select sum(`voting_power`) as `score` from `audition_vote` group by `audition_id`) as `scores`

查询是正确的,但我想重用变量“分数”

哦,你可以这样做:

var scores = Bookshelf.knex('audition_vote')
   .sum('voting_power as score')
   .groupBy('audition_id')
   .as('scores');
var topScores = Bookshelf.knex.distinct('score').from(scores.clone());

.as被忽略,除非它在子查询中,并且只有在其他地方改变scores查询时才需要克隆。

或者你可以这样做:

var scores = Bookshelf.knex('audition_vote')
   .sum('voting_power as score')
   .groupBy('audition_id');
var topScores = Bookshelf.knex.distinct('score').from(scores.clone().as('scores'));
此页面是否有帮助?
0 / 5 - 0 等级

相关问题

aj0strow picture aj0strow  ·  3评论

marianomerlo picture marianomerlo  ·  3评论

ghost picture ghost  ·  3评论

mtom55 picture mtom55  ·  3评论

PaulOlteanu picture PaulOlteanu  ·  3评论