简体   繁体   中英

How to find a last record for a record in first table in mysql

I have a first table of users which have a boolean field to represent a user as active and in the second table i have user audits .

I have to find when a user is activated last time, so that means i have many number of audits just have to get last activated audit for a currently active user.

Fields of User Table:

user_id, username, firstname, lastname, email, isactive

Fields of Audit Table:

user_id, audit_date, actiontype

You can use a temp table with max audti_date

select * from user 
INNER  JOIN  (select user_id, max(audit_date) 
             from AUDIT group by user_id) a on a.user_id = USER.user_id 
where user.isactive = true

I guess You want this:

SELECT 
  user_table.*, MAX(audit_table.audit_date) AS last_activated
FROM audit_table 
LEFT JOIN user_table ON (user_table.user_id = audit_table.user_id) 
WHERE 
  audit_table.user_id = 5 AND audit_table.actiontype = 'activate' 
  AND user_table.isactive = 1;

If You want list of activated users with last activation date:

SELECT 
  user_table.*, MAX(audit_table.audit_date) AS last_activated 
FROM audit_table 
LEFT JOIN user_table ON (user_table.user_id = audit_table.user_id) 
WHERE 
  audit_table.actiontype = 'activate' AND user_table.isactive = 1
GROUP BY audit_table.user_id;

You can get the most recent date using aggregation:

select user_id, max(audit_date) as maxad
from user_audits
where isactive = 1
group by user_id;

You can get all the information from the audit table by joining it to the above information:

select au.*
from user_audits au join
     (select user_id, max(audit_date) as maxad
      from user_audits
      where isactive = 1
      group by user_id
     ) u
     on au.user_id = u.user_id and au.audit_date = u.maxad and au.isactive = 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