0

我有 2 张桌子:UserSession. 对于每个用户,我想知道会话表中的最后一条记录是否是去年创建的。

我尝试了以下方法,但它不起作用:

SELECT *
FROM(
    SELECT MAX(`Session`.acDateF) as MaxDateF
    FROM `Session`
    WHERE `Session`.acType='1'
) as AcDate
GROUP BY `Session`.userId) 
WHERE YEAR(`Session`.acDateF) =YEAR(CURRENT_DATE())-1

如果用户今年在表中有记录,则Session它不会出现在结果中。

4

3 回答 3

2

你的问题不是很清楚,但听起来你想要这样的东西:

SELECT * 
FROM `Session` s
INNER JOIN 
(
    SELECT MAX(`Session`.acDateF) as MaxDateF, `Session`.userId
    FROM `Session`
    WHERE `Session`.acType='1'
        AND YEAR(s.acDateF) =YEAR(CURRENT_DATE())-1
    GROUP `Session`.userId
) as AcDate
    ON s.userId = AcDate.userId
    AND s.acDateF = AcDate.MaxDateF;

或者,如果您想要用户数据:

SELECT * 
FROM `user` u
INNER JOIN 
(
    SELECT MAX(`Session`.acDateF) as MaxDateF, `Session`.userId
    FROM `Session`
    WHERE `Session`.acType='1'
        AND YEAR(s.acDateF) =YEAR(CURRENT_DATE())-1
    GROUP `Session`.userId
) as AcDate
    ON u.userId = AcDate.userId;    
于 2013-01-10T15:33:38.320 回答
0
SELECT
    MAX(`Session`.acDateF) as MaxDateF,
    `Session`.userId
FROM `Session`
WHERE `Session`.acType='1'
GROUP BY `Session`.userId
having MAX(YEAR(`Session`.acDateF)) as MaxDateF =YEAR(CURRENT_DATE())-1
于 2013-01-10T15:33:16.140 回答
0

这是一种方法。它使用子句中的相关子查询where来获取上一年的最后日期:

select *
from session s
where s.acDatef = (select MAX(se.acDatef)
                   from session s2
                   where s2.userid = s.userid and
                         YEAR(`Session`.acDateF) =YEAR(CURRENT_DATE())-1
                  )
于 2013-01-10T15:34:05.497 回答