首先分别解决每个问题:
SELECT A.UserID, MAX(TIME) AS LastLogin
FROM UserMaster A
LEFT JOIN UserWebActivity B
ON A.UserID = B.UserID
AND Activity = 'Login'
GROUP BY A.UserID
SELECT A.UserID, COUNT(Activity) AS Logins
FROM UserMaster A
LEFT JOIN UserWebActivity B ON A.UserID = B.UserID
AND Activity = 'Login'
AND TIME BETWEEN (NOW() - INTERVAL 3 MONTH) AND NOW( )
GROUP BY A.UserID
分别测试它们以确保这些查询中的每一个都按您的意愿工作,并在必要时进行调整。
然后,当您对它们都起作用感到高兴时,将结果合并在一起:
SELECT T1.UserID, T1.LastLogin, T2.Logins
FROM
(
SELECT A.UserID, MAX(TIME) AS LastLogin
FROM UserMaster A
LEFT JOIN UserWebActivity B
ON A.UserID = B.UserID
AND Activity = 'Login'
GROUP BY A.UserID
) AS T1
JOIN
(
SELECT A.UserID, COUNT(Activity) AS Logins
FROM UserMaster A
LEFT JOIN UserWebActivity B
ON A.UserID = B.UserID
AND Activity = 'Login'
AND TIME BETWEEN (NOW() - INTERVAL 3 MONTH) AND NOW()
GROUP BY A.UserID
) AS T2
ON T1.UserID = T2.UserID
这将允许 MySQL 为不同的查询充分利用索引。