简体   繁体   中英

mysql WHERE and LAST

I need to get from base a last record where code = variable and complete = 0 .

I use this SQL:

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

For example DB:

email - code - complete - date
test@email - code1 - 0 - 1111111
test@email - code2 - 0 - 2222222

If variable $code will be one of values in DB, then query will perfectly work, but I also need to check is it the last record with this email or not, but I don't understand how.

Use ORDER BY with LIMIT to limit the results to the last record (ee ORDER BY most recent date):

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

Try this...

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 

Use INNER JOIN with 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'

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