Salar
Salar

Reputation: 5509

knex.js join two subqueries (nested queries)

I want to join two subqueries in knex.js and produce this sql result.

SELECT '*'
FROM
    (
    SELECT
        `*`
    FROM
        `A`
    WHERE
        A.id = 1
) AS `t1`
LEFT JOIN
    (
    SELECT
        *
    FROM
        `B`
    WHERE
       B.id = 2
) AS `t2`
ON
    `t1`.`c` = `t2`.`d`

How can I do that?

Upvotes: 14

Views: 21475

Answers (2)

Pouya Khalilzad
Pouya Khalilzad

Reputation: 1787

use this code :

knex
        .select('*')
        .from(function () {
            this.select('*').from('A')
                .where('id',1)
                .as('t1');
        })
        .leftJoin(
            knex('B').where('id',2).as('t2')
            , function () {
                this.on('t1.c', '=', 't2.d');
            })

Upvotes: 18

Mikael Lepistö
Mikael Lepistö

Reputation: 19728

knex(
  knex('A').where('A.id',1).as('t1')
).leftJoin(
  knex('B').where('B.id', 2).as('t2'), 
  't1.c', 
  't2.d'
)

Upvotes: 14

Related Questions