sql - 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
)
....
解决方案
包括设备计数,然后修改您当前的逻辑以获取不同的位置计数:
$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();
这应该起作用的原因是纯设备计数应该已经反映了真实计数,因为它使用了连接中的最后一个表。对于位置,我们采用不同的计数来消除由于加入设备表而可能发生的重复计数。
推荐阅读
- excel - 读取 CSV 文件并写入特定工作表中的已知位置
- swift - Swift UIView zPosition 问题,视图与其他视图重叠
- javascript - 我如何只读值属性?
- node.js - 如何在社交媒体应用程序中显示包含群组参与者数量的群组列表?
- python - 根据具有预分配唯一标识符的数据帧为数据帧行分配唯一标识符
- python - 如何解决 ModuleNotFoundError:虚拟环境中没有名为“skimage”的模块
- android-studio - 不能全部导入 - Android Studio
- android - 如何使 .proto 定义文件在 Android Studio (4.2) 的 Android 视图中可见?
- php - 将属性路径分配给变量时,PHP simplexmlelement 找不到属性
- python - 如何保存选项卡式 json 文件