Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knex.js join two subqueries (nested queries)

Tags:

knex.js

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?

like image 265
Salar Avatar asked Mar 12 '18 16:03

Salar


People also ask

Can subqueries be JOINed?

A subquery can be used with JOIN operation. In the example below, the subquery actually returns a temporary table which is handled by database server in memory. The temporary table from the subquery is given an alias so that we can refer to it in the outer select statement.

Can we use joins inside a nested query?

Yes, you can have a Select in a Join.

Can you join two or more tables data using subqueries yes or no?

Yes, most databases therefore includes it as an optimization step to convert subqueries into joins when it is analyzing your query.

Are nested queries better than joins?

The retrieval time of the query using joins almost always will be faster than that of a subquery. By using joins, you can maximize the calculation burden on the database i.e., instead of multiple queries using one join query.


2 Answers

knex(
  knex('A').where('A.id',1).as('t1')
).leftJoin(
  knex('B').where('B.id', 2).as('t2'), 
  't1.c', 
  't2.d'
)
like image 132
Mikael Lepistö Avatar answered Oct 24 '22 00:10

Mikael Lepistö


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');
            })
like image 28
Pouya Khalilzad Avatar answered Oct 23 '22 23:10

Pouya Khalilzad