如何使用 mysql phpmyadmin 对三个表中的记录进行计数和求和?

how count and sum records in three tables using mysql phpmyadmin?

我是这个社区的新手,也是 MySQL 的新手。

需要COUNT客户和SUM每个推荐人的佣金分别使用MySQL查询。

推荐人table

id referrer_name
1 referre1
2 referre2
3 referre3
4 referre4

客户table

id referrer_id client_name
1 1 client1
2 1 client2
3 2 client3
4 3 client4
5 4 client5

佣金table

id client_id commission
1 1 20
2 1 32
3 3 24
4 4 15

我想使用以上 3 tables 实现以下输出。

referrer_id referrer_name total_client total_commission
1 referre1 2 52
2 referre2 1 24
3 referre3 1 15
4 referre4 1 0

我试过以下查询

 SELECT referrer.referrer_name as name,
(SELECT COUNT(*) FROM client WHERE client.referrer_id=referrer.id) as total_client,
(SELECT SUM(commission) FROM commission WHERE commission.client_id=client.id) as total_commission FROM referrer LEFT JOIN client ON client.referrer_id=referrer.id GROUP BY name;

阅读Mysql join and Aggregate Functions

SELECT t2.referrer_id,
       t1.referrer_name,
       COUNT(DISTINCT t2.id) AS total_client,
       SUM(t3.commission)                 AS total_commission
FROM referrer t1
         JOIN client t2 ON t1.id = t2.referrer_id
         JOIN commission t3 ON t2.id = t3.client_id
GROUP BY t1.referrer_id