Based on typeORM docs on using subqueries, there are explained how to create subqueries. Example:
const qb = await getRepository(Post).createQueryBuilder("post");
const posts = qb
.where("post.title IN " + qb.subQuery().select("user.name").from(User, "user").where("user.registered = :registered").getQuery())
.setParameter("registered", true)
.getMany();
But there is no equivalent as to what the SQL would be.
Supposed that I have the query which contains subqueries like the following:
SELECT a, TO_CHAR (MAX (jointable.f), 'MON YYYY') as f,
t3.c, t3.d, t1.e
FROM table1 t1
LEFT JOIN table2 t2 ON t2.e = t1.e
JOIN table3 t3 ON t3.d = t2.d
JOIN
(SELECT f, t4.g, t5.e, t6.h
FROM table4 t4
JOIN table5 t5 ON t4.g = t5.g
JOIN table6 t6 ON t6.g = t4.g
AND (t6.i = 2
OR (t6.i = 1 AND j = 1)
)
WHERE t4.k = 4
) jointable ON t1.e = jointable.e
WHERE jointable.h = :h
AND(:d = 3 OR
t3."d" = :d
)
GROUP BY a, t3.c, t3.d, t1.e
ORDER BY a ASC
How should I use the typeORM query builder function for the SQL query above?
Assuming that I had created entities related to all table being used on the query above.
I hope this answer could help others to use TypeORM subquery.
I was using
'('+subquery.getQuery()+')'for getting the subquery select query as an equivalent toBased on what I understand:
Joinactually is equal toinner join.selectis and equivalent ofselectin SQL. You could also addaliases(as in SQL)..addSelectis similar to, in selectThere are two types of results you can get using select query builder: entities or raw results. To describe whether you want the data as entities (
getOneandgetMany) or what it is(getRawOneandgetRawMany).