Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

三张表联动查询,查询该部门有几个订单,订单跟用户表关联,用户表跟部门关联。

部门表 toadmin_auth_department
用户表 touser_auth_user
订单表 business

关系是:
部门表里有a,b,c,d部门
用户里有1,2,3是a部门的,4,5是b的。一个用户只能对应一个部门
订单表是每个订单对应一个用户。

我想查询a部门下有几个订单。b部门下有几个订单。

刚学完前端,现在后端偶尔要帮忙写,用的TP6框架。对后端跟数据库的操作实属不熟。希望各位大佬给个思路


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

好啦 问题自己想办法解决了 解决方法是用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();
   
  

得出的数据
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...