2013-03-20 64 views
0

我需要從基地獲得最後一條記錄,其中code = variablecomplete = 0mysql WHERE和LAST

我用這個SQL:

SELECT email, date FROM users_recovery WHERE restore_key = '" . $code . "' AND complete = '0' 

例如DB:

email - code - complete - date 
[email protected] - code1 - 0 - 1111111 
[email protected] - code2 - 0 - 2222222 

如果變量$code將在DB值中的一個,那麼查詢將很好地工作,但我還需要檢查這是否是電子郵件地址的最後一個記錄,但我不明白。

回答

0

嘗試......

SELECT b.email, b.date, b.complete, b.code 
FROM (SELECT email, 
       Max(date) AS date 
     FROM users_recovery 
     GROUP BY email 
     WHERE code = variable 
       AND complete = 0) a 
     JOIN users_recovery b 
     ON b.email = a.email 
      AND b.date = a.date 
0

使用ORDER BYLIMIT限制結果到最後一條記錄(EE ORDER BY最近的日期):

SELECT 
    email, 
    date 
FROM 
    users_recovery 
WHERE 
    restore_key = '" . $code . "' 
AND complete = '0' 
ORDER BY 
    date DESC 
LIMIT 1 
+0

它不會工作,因爲restore_key是唯一的值,但我需要通過電子郵件檢查最後一條記錄。 – user2058653 2013-03-20 17:50:29

0

使用INNER JOIN與MAX( )

SELECT 
    email, 
    date 
FROM users_recovery AS ur 
    INNER JOIN (SELECT 
     MAX(DAte) AS date 
      FROM users_recovery) AS url 
    ON url.date = ur.date 
WHERE restore_key = '" . $code . "' 
    AND complete = '0'