MySQL 3表联接,其中一个表的计数和另一个表的最大时间戳

时间:2019-01-25 13:53:19

标签: mysql join

我有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;

1 个答案:

答案 0 :(得分:1)

您应该计算座席在a = "https://www.reddit.com/comments/ado0ym/use_reddit_coins_to_award_gold_to_your_favorite/" b = "aaaaaaa" c = "somthing random" if b or c in a: print("true") else: print("false") # Results return True 表中的唯一记录数。您可以在agentclients列的DISCTINCT的帮助下完成此操作

agentclients.id