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?
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.
Yes, you can have a Select in a Join.
Yes, most databases therefore includes it as an optimization step to convert subqueries into joins when it is analyzing your query.
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.
knex(
knex('A').where('A.id',1).as('t1')
).leftJoin(
knex('B').where('B.id', 2).as('t2'),
't1.c',
't2.d'
)
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');
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With