Reputation: 111
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
Upvotes: 0
Views: 66
Reputation: 19372
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;
Upvotes: 1
Reputation: 1269773
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
Upvotes: 1
Reputation: 133370
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
Upvotes: 1