Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

277
Views
how to write a subquery inside join statement

This is my subquery:

const subquery = async () => {
  return await knex.select('*')
    .from('contracts')
    .where('estate_id', '=', estateid)
}

And this is how I'm inserting it into the join statement:

const data = await knex('clients')
  .join(await subquery(), 'clients.client_id', 'contracts.client_id')

But this result in an error, my question is what is the proper way to write a subquery and then include it inside a join statement, using async/await.

In the docs there is a mention on subqueries but is not for the join case and I fail at trying to adapt it to a join case:

knex('users').where('votes', '>', 100)

const subquery = knex('users')
  .where('votes', '>', 100)
  .andWhere('status', 'active')
  .orWhere('name', 'John')
  .select('id');

knex('accounts').where('id', 'in', subquery)
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

No need to await the subquery, you can just pass a function representing the subquery as the first argument to the join. i.e.

const data = await knex('clients')
    .join(function() {
        this.select('*')
        .from('contracts')
        .where('estate_id', '=', estateid);
    }, 'clients.client_id', 'contracts.client_id');

Note that the reference to knex changes from knex to this once inside the subquery. If you want to keep the subquery separate you should be able to do it like

const subquery = function() {
    this.select('*')
    .from('contracts')
    .where('estate_id', '=', estateid)
}
const data = await knex('clients')
  .join(subquery, 'clients.client_id', 'contracts.client_id')
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!