我想从表
quotationVersion
、中名为
quotation
的表列中选择最大值
getOneMaximumQuotationVersion() {
const query = this.createQueryBuilder("quotation");
query.select("MAX(quotation.quotationVersion)", "max");
// query.addSelect("MAX(quotation.quotationVersion)", "max");
return query.getOne();
}
如果要在选择子句中添加MAX、SUM等函数,则需要执行getRawOne()或getRawMany()。这将为您提供原始响应:
getOneMaximumQuotationVersion() {
const query = this.createQueryBuilder("quotation");
query.select("MAX(quotation.quotationVersion)", "max");
// query.addSelect("MAX(quotation.quotationVersion)", "max");
return query.getRawOne();
}
方法
getOne
和getMany
用于选择实际的数据库实体。如果选择计算值,则需要使用 getRawOne
(或对于多个值使用 getRawMany
)。请注意,返回的值是一个对象,其键是您在调用 select
时指定的别名;在您的情况下,别名称为 max
。
另外不要忘记操作的异步性质。
所以,我会像这样重写你的函数:
async getOneMaximumQuotationVersion() {
const query = this.createQueryBuilder("quotation");
query.select("MAX(quotation.quotationVersion)", "max");
const result = await query.getRawOne();
return result.max;
}
更多信息可以在官方文档中找到。
在我的例子中,我使用了这个简单的 repo 模式:
const [maxValueEntity] = await this.repo.find({
order: {
value: 'DESC',
},
take: 1,
});
对于更复杂的情况,您可以使用子查询:
const maxValueQuery = this.createQueryBuilder('entity')
.select('MAX(entity.value)')
.getQuery();
const maxValueEntity = await this.createQueryBuilder('entity')
.where(`entity.value = (${maxValueQuery})`)
.getOne();
const maxValueRaw = await this.createQueryBuilder('entity')
.select('MAX(enity.value)', 'max')
.getRawOne<{ max: string }>();
更多 typeorm 子查询测试用例这里📍
如果您来这里寻找如何在 typeorm 中为列提供最小值、最大值,那么这就是这样做的方法
@Column()
@IsInt()
@Min(0)
@Max(10)
rating: number;
欲了解更多详情,这里