簡體   English   中英

回送mysql查詢聚合

[英]aggregation on loopback mysql query

我想知道如何在環回查詢上進行聚合。我使用MySQL作為數據庫,在數據庫中有這樣一條記錄- { 'app_name': 'chrome', 'duration' : 10000 }, { 'app_name': 'WhatsApp', 'duration' : 25000 } and so on ,持續時間以毫秒為單位。 我正在使用angular 7作為前端,並且我想進行環回查詢以匯總所有記錄的持續時間,現在我正在進行如下查詢:

Apps.find({}).toPromise()
    .then(apps => {
        let result = apps.reduce((app, total) = {
            total += app.duration;
            return total
        }, 0)
        console.log(result);
    })
    .catch(err => {
        console.log(err);
     })

但是,使用這種方法,我可以得到持續時間的總和,但是如果我有數百萬個記錄,那么它不是一個可伸縮的解決方案,例如從數百萬個記錄進行迭代,然后求和持續時間。 我想知道MySQL的回送查詢中是否存在聚合。 我想要一個查詢-

Apps.find({
      aggregation: {
       sum: 'duration'
     }
    }).toPromise()
    .then(result => {
        console.log(result);
    })
    .catch(err => {
        console.log(err);
     })

這樣的事情。

LoopBack還不支持聚合。 我的建議是編寫一個自定義控制器方法,該方法將執行一個自定義SQL查詢以聚合結果。

// in your controller
export class MyController {
  constructor(
    @repository(AppRepository) protected appRepo: AppRepository
  ) {}

  // default CRUD methods scaffolded by lb4

  // custom method
  @get('/apps/durations')
  getDurations() {
    return this.appRepo.getAggregatedDurations();
  }
}

// in your AppRepository
export class AppRepository extends DefaultCrudRepository<
  App,
  typeof App.prototype.id,
  AppRelations
> {
  constructor(
    @inject('datasources.db') dataSource: juggler.DataSource,
    // ...
  ) {
    super(App, dataSource);
    // ...
  }

  // add a new method
  async getAggregatedDurations(): Promise<number> {
    // A mock-up SQL query, you may need to tweak it
    const result = await this.execute('SELECT SUM(duration) as total_duration FROM Apps');
    // I am not entirely sure what's the shape of result object,
    // you have to find out yourself how to access "total_duration" field 
    return result[0].total_duration;
  }
}

另請參閱API文檔以獲取execute方法: https//loopback.io/doc/zh/lb/apidocs.repository.executablerepository.execute.html和LoopBack 3.x文檔: https//loopback.io/doc/zh/ LB3 /執行本地-SQL.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM