输入特定列的选择最大值

问题描述 投票:0回答:4

我想从表

quotationVersion
 中名为 
quotation

的表列中选择最大值

代码

  getOneMaximumQuotationVersion() {
    const query = this.createQueryBuilder("quotation");
    query.select("MAX(quotation.quotationVersion)", "max");
    // query.addSelect("MAX(quotation.quotationVersion)", "max");
    return query.getOne();
  }
javascript typeorm
4个回答
11
投票

如果要在选择子句中添加MAXSUM等函数,则需要执行getRawOne()getRawMany()。这将为您提供原始响应:

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

5
投票

方法

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;
}

更多信息可以在官方文档中找到。


1
投票

在我的例子中,我使用了这个简单的 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 子查询测试用例这里📍


0
投票

如果您来这里寻找如何在 typeorm 中为列提供最小值、最大值,那么这就是这样做的方法

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

欲了解更多详情,这里

© www.soinside.com 2019 - 2024. All rights reserved.