2013-01-10 170 views
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表今年則沒有出現在結果的記錄。

+0

你想「爲AcDate」來到您的集團By語句後? – Melanie

回答

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