繁体   English   中英

如何获取一个查询的结果并将该列表用作第二个表上另一个查询的键?

[英]How to take the result of one query and use that list as a key for another query on a second table?

我的第一个查询将返回用户列表及其上次登录时间:

username   |       last_login
john            2020-04-12 00:01:23 
amy             2020-04-10 12:13:42
brad            2020-04-11 11:21:00
max             2020-04-09 03:33:00

然后,我想搜索另一个记录所有登录及其持续时间的表,并返回每个用户的最长登录时间。

username    |    login_time          |      logout_time       |    duration
john          2020-04-12 00:01:23        2020-04-12 00:10:23          9
amy           2020-04-10 12:13:42        2020-04-10 12:43:42          30
brad          2020-04-11 11:21:00        2020-04-11 12:21:00          60
john          2020-04-10 08:21:00        2020-04-10 08:45:00          24
amy           2020-04-10 07:00:42        2020-04-10 07:03:42          3
max           2020-04-09 03:33:00        2020-04-09 03:40:00          7

查询一:

select username, last_login from t1;

查询 2 以获取特定用户的最长连胜记录:

select duration from t2 where username='john' and duration=(select max(duration) from t2 where username='john')

我想要的结果是每个用户,他们的最后一次登录,以及最长的登录时间:

username    |        last_login         |    longest_login
john             2020-04-12 00:01:23                24
amy              2020-04-10 12:13:42                30
brad             2020-04-11 11:21:00                60
max              2020-04-09 03:33:00                7

我不确定如何使用查询 1 中找到的每个用户名执行第二个查询,然后组合结果。

您可以join和聚合:

select q1.username, q1.lastlogin, max(t.duration)
from firstquery q1 join
     othertable t
     on t.username = q1.username
group by q1.username, q1.lastlogin;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM