I’m trying to write a query to join a user table to an activity logging table and return the following for each user:
A) The time they last logged in.
B) The number of logins in the last 3 months.
This is what I have come up with so far:
SELECT A.UserID, COUNT( Activity ) AS Logins, MAX( TIME ) AS LastLogin
FROM UserMaster A
LEFT JOIN UserWebActivity B ON A.UserID = B.UserID
AND Activity = 'Login'
AND TIME BETWEEN DATE_SUB( NOW( ) , INTERVAL 3 MONTH ) AND NOW( )
GROUP BY A.UserID
This almost works, but it doesn’t return the latest login for any user that hasn’t logged in within the last 3 months. How can I get count() and max() to work together properly?
First solve each problem separately:
Test them separately to ensure that each of these queries works as you want, and adjust them if necessary.
Then when you are happy that they both work, join the results together:
This will allow MySQL to make best use of the indexes for the different queries.