Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

269
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda