We have timestamps for various things across the site. I’m looking for a way to get users who are “online” or have been active in the past 20 minutes. Im also trying to sort them by an intersection of the latest timestamp in multiple columns across multiple tables.
SELECT user.userID, user.username, GREATEST(
(SELECT MAX(notifications.noteTime) FROM notifications WHERE notifications.creatorID = user.userID),
challengesRead.lastRead,
notificationsRead.lastRead) AS realtime
FROM user
LEFT JOIN challengesRead ON challengesRead.userID = user.userID
LEFT JOIN notificationsRead ON notificationsRead.userID = user.userID
LEFT JOIN notifications ON notifications.creatorID = user.userID
LEFT JOIN challenges ON challenges.userID = user.userID
WHERE timestampdiff(minute, realtime, now()) < 20
GROUP BY user.userID
ORDER BY realtime DESC
My questions.
1) Timestampdiff doesn’t seem to recognize realtime? However, recalculating GREATEST() in timestampdiff does work but seems repetitive.
2) Yikes, this beast takes forever to run, whats the best way to optimize?
3) What is a better way to do this?
you could make a new table like ‘latest_activity’ and add triggers to populate with user_id and timestamp… that would at least give you one place to query.