Typeorm subquery add select

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

Upvotes: 11

Views: 34058

Answers (2)

Kartik Raja S
Kartik Raja S

Reputation: 728

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();

Upvotes: 22

hnakao11
hnakao11

Reputation: 865

You can use subselects in SELECT statements:

let query = await this.createQueryBuilder('t1')
    .select()
    .innnerJoin('t1.t2', 't2', 't1.a = t2.a')
    .addSelect(subQuery => {        
         return subQuery            
              .select('_t1.a')            
              .from(Table1, '_t1')
              .where('_t1.b = t2.a');    
     }, 'MaxT1')
     .getRawMany()

You can find more here: https://orkhan.gitbook.io/typeorm/docs/select-query-builder

Upvotes: 1

Related Questions