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`

クエリは正しいですが、変数「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 評価