在 Laravel Query Builder 中使用 group by 聚合查询

Aggregate queries in Laravel Query Builder with group by

我有一只table只鸟。

我想在单个查询中计算每种鸟类的数量。

如果可能,我想在 Eloquent 中将这些查询组合成一个查询。

 select count(id) as count1 from birds where kind = a;

 select count(id) as count2 from birds where kind = b;

 select count(id) as count2 from birds where kind = c;

我试过

$first = DB::table('birds')->selectRaw('count(id) as count1')->where('kind','a');
DB::table('birds')->selectRaw('count(id) as count2')->where('kind','b')->unionAll($first)->get();

我认为工会没有给我想要的东西。

我只需要像

这样的东西
DB::raw(' (select count(id) from birds where kind = a) as count1 ', ' (select count(id)  from  birds where kind = a) as count2  ', ' (select count(id) from birds where kind = a) as count3 ')

我想合并查询

喜欢

Select ( select count(id)  from birds where kind = 'a') as count1, ( select count(id)  from birds where kind = 'b') as count2,  ( select count(id)  from birds where kind ='c') as count3 from birds ;

。请告诉我如何实现它。

特别学习 SQL、group byaggregates

这是您在 Laravel 中需要的:

DB::table('birds')
  ->selectRaw('count(id) as count, kind')
  ->groupBy('kind')
  ->lists('count', 'kind');
  // or get()

lists 将 return 如下所示的数组:

array(
  'kind_1' => '15',
  'kind_2' => '10',
  ...
);

get 会 return 一个 stdObjects 的数组,所以可能不是你想要的:

array(
  0 => StdObject {
    'kind' => 'kind_1',
    'count' => '15'
  },
  1 => StdObject {
    'kind' => 'kind_2',
    'count' => '10'
  },
  ...
);

如果您只想获得特定的 kinds 鸟类,请使用 whereIn:

DB::table('birds')
  ->selectRaw('count(id) as count, kind')
  ->groupBy('kind')
  ->whereIn('kind', ['kind_1', 'kind_2', 'kind_3'])
  ->lists('count', 'kind');