Typeorm subquery add select

Reyhan Fikran Dzikriansyah picture Reyhan Fikran Dzikriansyah · Mar 13, 2019 · Viewed 14.8k times · Source

I am new for using typeorm and this is the second time I am confused with typeorm, I have the following query :

SELECT t1.a,t1.b,t2.a
  (SELECT TOP 1 t1.a
  FROM table1 t1
  WHERE t1.b = t2.a
  ORDER BY t1.a DESC
  ) AS MaxT1
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.a = t2.a

I tried this:

let query = await getManager()
  .createQueryBuilder(Bid, 'bid')
    .select([
      'l.ID_anv_Lot',
      'l.LotNumber',
      'w.WineryName',
      'bid.BidAmount',
      'bid.ProxyBidAmount',
      'er.ID_Contact'
    ])
    .addSelect(Table1, t1)
    .innerJoin(Lot, 'l', 'l.lotNumber = bid.lotNum AND l.paddleNumber = bid.paddleNumber')

but the result is all of the rows on table1

Answer

Kartik Raja S picture Kartik Raja S · Mar 28, 2019

This Example may help you to perform sub query execution:

const posts = await connection.getRepository(Post)
            .createQueryBuilder("post")
            .where(qb => {
                const subQuery = qb.subQuery()
                    .select("usr.name")
                    .from(User, "usr")
                    .where("usr.registered = :registered")
                    .getQuery();
                return "post.title IN " + subQuery;
            })
            .setParameter("registered", true)
            .orderBy("post.id")
            .getMany();