[英]Output data from two tables using most recent entry
I have done a good search for a similar question, but with no joy. 我已经很好地寻找了类似的问题,但并不高兴。 I think the answer to my question is based around DISTINCT, GROUP and UNION, but just can't put the together in any way which makes sense. 我认为我的问题的答案基于DISTINCT,GROUP和UNION,但不能以任何有意义的方式将它们组合在一起。
I have 2 tables: 我有2张桌子:
users(id, username)
activitylog(id, userid, usernamedisp, activity)
Sample data: 样本数据:
users
id, username
1, Joe Bloggs
2, Jane Doe
3, John Smith
activitylog
id, userid, usernamedisp, activity
1, 3, John Smith , logged in
2, 3, John Smith , visited about us page
3, 1, Joe Bloggs , logged in
4, 3, John Smith , logged out
5, 2, Jane Doe , logged in
6, 1, Joe Bloggs , logged out
7, 2, Jane Doe , visited about us page
(there is another unrelated but valid reason why the user's name appears in both tables) (还有另一个不相关但有效的原因,使得用户名同时出现在两个表中)
I want the output to list the users in order of users.id along with activitylog.username and finally only the most recent activitylog.activity, which should look as follows: 我希望输出按users.id和activitylog.username的顺序列出用户,最后只列出最新的activitylog.activity,其外观应如下所示:
User, Username , Last Activity
1, Joe Bloggs, logged out
2, Jane Doe , visited about us page
3, John Smith, logged out
While I could do this by running a query inside a loop on each result (SELECT activity from activitylog where userid = $foo ORDER BY id DESC, LIMIT 0,1) - I would rather run it all off in one nice clean piece of code as the number of users could be between 50-100 and that's too many queries for my comfort. 尽管我可以通过在每个结果的循环内运行查询来做到这一点(从activitylog中的SELECT活动,其中userid = $ foo ORDER BY ID DESC,LIMIT 0,1)-我宁愿用一个不错的干净代码全部运行它因为用户数量可能在50到100之间,这让我感到很舒服。
I'm sure this is possible, but I just can't seem to put it together. 我敢肯定这是可能的,但我似乎无法将其放在一起。
YOu need a two-part query: one to get the list of usersIDs and their "max" id, which would be their latest activity. 您需要一个分为两部分的查询:一个用于获取用户ID列表及其“最大” ID(这是他们的最新活动)。 Then a container query which takes those IDs and fetches the rest of the information: 然后进行容器查询,获取这些ID并提取其余信息:
SELECT activitylog.userid, users.username, activitylog.activity
FROM activitylog
LEFT JOIN users ON activitylog.userid = users.id
WHERE activitylog.id IN (
SELECT MAX(id)
FROM activitylog
GROUP BY userid
)
Contd. 续。 from discussion in comments... 从评论中的讨论...
This query should get you the next solution set you are looking for. 该查询将为您提供您正在寻找的下一个解决方案集。
SELECT AL.userid
,users.username
,AL.activity
FROM users
LEFT JOIN (
SELECT activitylog.userid
,activitylog.activity
FROM activitylog
WHERE activitylog.id IN (
SELECT MAX(id)
FROM activitylog
GROUP BY userid
)
) as AL ON AL.userid = users.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.