首页 > 解决方案 > Laravel 查询 - 从 3 个不同的表中计数和分组

问题描述

我在 LARAVEL 和 SQL 中迈出了第一步,我正在尝试构建一个查询,该查询返回我拥有的部门列表,同时计算每个部门的位置总数和每个位置的设备总数。

所以我尝试了以下方法:

$dep = DB::table('departments')
       ->leftjoin('locations','departments.dep_id','=','locations.department')
       ->leftjoin('devices','locations.id','=','devices.location')
       ->select('departments.name',DB::raw('count(locations.id) as locationcount'))
       ->groupby('departments.name')
       ->get();

这返回给我以下信息:

Illuminate\Support\Collection Object
(
    [items:protected] => Array
        (
            [0] => stdClass Object
                (
                    [name] => Interior Design
                    [locationcount] => 3
                )

            [1] => stdClass Object
                (
                    [name] => IT
                    [locationcount] => 29
                )

            [2] => stdClass Object
                (
                    [name] => Marketing
                    [locationcount] => 0
                )

            [3] => stdClass Object
                (
                    [name] => Operations
                    [locationcount] => 13
                )

        )

)

但是这里我们看到的计数是针对设备的,而不是针对位置的。有没有办法实现这个查询?或者我需要做一个循环之后?我正在寻找这样的结果:

Illuminate\Support\Collection Object
    (
        [items:protected] => Array
            (
                [0] => stdClass Object
                    (
                        [name] => Interior Design
                        [locationcount] => 2
                        [devicecount] => 10
                    )

....

标签: sqllaravel

解决方案


包括设备计数,然后修改您当前的逻辑以获取不同的位置计数:

$dep = DB::table('departments')
    ->leftjoin('locations', 'departments.dep_id', '=', 'locations.department')
    ->leftjoin('devices', 'locations.id', '=', 'devices.location')
    ->select('departments.name',
             DB::raw('COUNT(DISTINCT locations.id) AS locationcount'),
             DB::raw('COUNT(devices.id) AS devicecount'))
    ->groupby('departments.name')
    ->get();

这应该起作用的原因是纯设备计数应该已经反映了真实计数,因为它使用了连接中的最后一个表。对于位置,我们采用不同的计数来消除由于加入设备表而可能发生的重复计数。


推荐阅读