简体   繁体   中英

Typeorm select max with specific column

I want to select maximum value from a table's column named quotationVersion from table quotation ,

Code

  getOneMaximumQuotationVersion() {
    const query = this.createQueryBuilder("quotation");
    query.select("MAX(quotation.quotationVersion)", "max");
    // query.addSelect("MAX(quotation.quotationVersion)", "max");
    return query.getOne();
  }

If you want to add functions like MAX , SUM in the selection clause, you need to do getRawOne() or getRawMany() . This will give you the raw response:

getOneMaximumQuotationVersion() {
    const query = this.createQueryBuilder("quotation");
    query.select("MAX(quotation.quotationVersion)", "max");
    // query.addSelect("MAX(quotation.quotationVersion)", "max");
    return query.getRawOne();
  }

Methods getOne and getMany are used for selecting actual database entities. If you select a calculated value, you need to use getRawOne (or getRawMany for multiple values). Notice that the returned value is an object with the keys being the aliases you specified when calling select ; in your case the alias is called max .

Also don't forget the asynchronous nature of the operation.

So, I'd rewrite your function like this:

async getOneMaximumQuotationVersion() {
  const query = this.createQueryBuilder("quotation");
  query.select("MAX(quotation.quotationVersion)", "max");
  const result = await query.getRawOne();
  return result.max;
}

More information could be found in the official documentation .

If you have come here finding out how to give min, max value to column in typeorm then this is the way to do it

@Column()
@IsInt()
@Min(0)
@Max(10)
rating: number;

For further details, here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM