Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Subquery in "from" clause using another instance of knex #538

Closed
sandrocsimas opened this issue Oct 22, 2014 · 3 comments
Closed

Subquery in "from" clause using another instance of knex #538

sandrocsimas opened this issue Oct 22, 2014 · 3 comments
Labels

Comments

@sandrocsimas
Copy link

Hi!
I have this query:

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

and i want to wrap this query like:

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()) prints

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

How to use the variable "scores" inside from() ????

@tgriesser
Copy link
Member

What's the query you're ultimately looking to generate?

@sandrocsimas
Copy link
Author

The last one:

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

The query is right, but i want to reuse the variable "scores"

@sandrocsimas sandrocsimas changed the title Subquery in from using another instance of knex Subquery in "from" clause using another instance of knex Oct 22, 2014
@tgriesser
Copy link
Member

Oh, you can just do:

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());

The .as is ignored unless it's within a subquery, and the clone is only necessary if you're mutating the scores query elsewhere.

Or you could do:

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'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants