3

我正在尝试编写一个查询以将用户表连接到活动记录表并为每个用户返回以下内容:

A) 他们上次登录的时间。

B) 最近 3 个月的登录次数。

到目前为止,这是我想出的:

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  

这几乎可以工作,但它不会返回最近 3 个月内未登录的任何用户的最新登录信息。如何让 count() 和 max() 正常工作?

4

3 回答 3

4

首先分别解决每个问题:

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 为不同的查询充分利用索引。

于 2012-06-25T18:34:12.347 回答
3

您可以CASE在您的COUNT:

SELECT A.UserID,
  COUNT(
    CASE WHEN TIME BETWEEN DATE_SUB( NOW( ) , INTERVAL 3 MONTH ) AND NOW( )
    THEN Activity
  END ) AS Logins,
  MAX( TIME ) AS LastLogin  
FROM UserMaster A  
LEFT JOIN UserWebActivity B ON A.UserID = B.UserID  
AND Activity =  'Login'  
GROUP BY A.UserID

但是,如果您有大量数据,此解决方案的效率将低于 @MarkByers。

于 2012-06-25T18:35:11.597 回答
0

就像另一个疯狂的想法 - 而不是 MAX( TIME )

coalesce(max(time), (select max(time) from UserWebActivity where ...) )
于 2012-06-25T18:38:25.453 回答