简体   繁体   中英

Subquery to obtain last record

I have 2 tables: User and Session . For each User, I would like know if the last record in session table was created last year.

I tried the following, but it doesn't work:

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

If the User has a record in the Session table this year it doesn't appear in the result.

Your question is not very clear, but it sounds like you want something like this:

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;

Or if you want the user data:

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;    
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

Here is a way. It uses a correlated subquery in the where clause to get the last date for the previous year:

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
                  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM