部门表 toadmin_auth_department
用户表 touser_auth_user
订单表 business
关系是:
部门表里有a,b,c,d部门
用户里有1,2,3是a部门的,4,5是b的。一个用户只能对应一个部门
订单表是每个订单对应一个用户。
我想查询a部门下有几个订单。b部门下有几个订单。
刚学完前端,现在后端偶尔要帮忙写,用的TP6框架。对后端跟数据库的操作实属不熟。希望各位大佬给个思路
好啦 问题自己想办法解决了 解决方法是用LEFT JOIN跟GROUP BY
下面是sql
SELECT
d.id,
d.parent_id,
d.name,
COUNT( a.employee ) AS nums
FROM
toadmin_auth_department d
LEFT JOIN touser_auth_user u ON d.id = u.department_id
LEFT JOIN business a ON a.employee = u.id and a.record_time >= '2020-11-01 09:51:24'
GROUP BY
d.id,d.parent_id,d.name;
TP6是这样写
$field = 'd.id, d.parent_id, d.name, COUNT( a.employee ) AS nums';
$data['list'] = Db::name("toadmin_auth_department")
->alias('d')
->leftJoin(['touser_auth_user' => 'u'], 'd.id = u.department_id')
->leftJoin(['business' => 'a'], "a.employee = u.id and a.record_time >= '".$record_time."'")
->group('d.id,d.parent_id,d.name')
->where($where)->field($field)->page($params['page'], $params['size'])->order('d.id desc')->select()->toArray();
得出的数据