简体   繁体   English

Typeorm 如何使用 Where 子句获取 Min 字段?

[英]Typeorm How Can I get Min field with Where clause?

I use Typeorm and nestjs in my project.我在我的项目中使用 Typeorm 和 nestjs。 I have Schema:我有架构:

export class GroupEntity implements IGroup {
  // Attributes
  @PrimaryGeneratedColumn({ type: 'string' })
  public id: string;

  @Column({ type: 'string', nullable: false })
  public userId: string;

  @Column({ type: 'int2' })
  public syncStatus: number;
}

I want to get min sync status by userId where syncStatus is not null我想通过 userId 获取最小同步状态,其中 syncStatus 不为空

exampleData:示例数据:

[{
  id: "1",
  userId: "101",
  syncStatus: 2
}, {
  id: "2",
  userId: "101",
  syncStatus: 3
}, {
  id: "2",
  userId: "105",
  syncStatus: -5
}, {
  id: "2",
  userId: "101",
  syncStatus: null
}]

expected result预期结果

2
or row with value 2

Big thx!非常感谢!

You simply need to use MIN , Here's how:您只需要使用MIN ,方法如下:

return this.groupRepository.createQueryBuilder('group')
.select("MIN(group.syncStatus)",'syncStatus')
.addSelect(['group.id','group.userId'])
.where('group.userId = :user", {
    user,
  })
.andWhere('group.syncStatus is not null')
.getRawOne();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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