[英]MySQL 3 table join with count from one table and max timestamp from another
我有3个表格,样本数据如下。 我正在尝试获取有关代理名称,该代理的客户端数量以及该代理上次登录的时间的报告。如果该代理没有客户端,他将没有任何记录(但可以进行最后一次登录)日期)。 相反,代理有可能拥有客户,但从未登录过。
table agents
| id | first | last |
----------------------------------------
| 1 | dave | schultz |
| 2 | bobby | clarke |
| 3 | ed | hospidar |
| 4 | derek | smith |
table agentclients
| id | agentid | clientid |
----------------------------------------
| 1 | 2 | 345 |
| 2 | 3 | 347 |
| 3 | 3 | 221 |
| 4 | 1 | 567 |
table loginhistory
| id | userid | usertype | ts
-------------------------------------------------------
| 1 | 2 | A | 2018-11-17 14:16:44 |
| 2 | 3 | A | 2018-11-24 20:46:16 |
| 3 | 4 | A | 2018-11-27 13:07:58 |
| 4 | 1 | A | 2019-01-05 13:45:01 |
| 5 | 4 | A | 2019-01-19 06:36:23 |
| 6 | 3 | A | 2019-01-24 02:13:44 |
Results:
agent id | agent name | clients | last login
-------------------------------------------------------
1 | dave schultz | 1 | 2019-01-05 13:45:01
2 | bobby clark | 1 | 2018-11-17 14:16:44
3 | ed hospidar | 2 | 2019-01-24 02:13:44
4 | derek smith | 0 | 2018-11-27 13:07:58
我似乎可以得到计数或最大登录数,但是如果我尝试全部加入3个,则计数不正确。
SELECT a.id, a.first, a.last, count(ac.clientid) as 'client count'
FROM agents a
LEFT JOIN agentclients ac on a.id = ac.agentid
WHERE a.agentdeleted = 0
GROUP BY ac.agentid;
用于计数客户
如果我尝试添加max(),计数将中断:
SELECT a.id, a.first, a.last, count(ac.clientid) as 'client count',
max(l.ts) AS 'lastlogin'
FROM agents a
LEFT JOIN agentclients ac on a.id = ac.agentid
LEFT JOIN loginhistory l on l.userid = a.aid and l.usertype = 'A'
WHERE a.agentdeleted = 0
GROUP BY ac.agentid;
您应该在agentclients
表中计算代理的唯一记录数量。 您可以通过agentclients.id
列在agentclients.id
帮助下DISCTINCT
agentclients.id
SELECT a.id,
a.first,
a.last,
COUNT( DISTINCT ac.id) as 'client count',
max(l.ts) AS 'lastlogin'
FROM agents a
LEFT JOIN agentclients ac on a.id = ac.agentid
LEFT JOIN loginhistory l on l.userid = a.aid and l.usertype = 'A'
WHERE a.agentdeleted = 0
GROUP BY ac.agentid;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.