我有第一个用户表,其中有一个布尔字段表示用户为active
,而在第二个表中我有用户audits
。
我必须找到上次激活用户的时间,这意味着我有许多audits
只需要为当前audit
用户激活active
。< / p>
用户表的字段:
user_id, username, firstname, lastname, email, isactive
审计表的字段:
user_id, audit_date, actiontype
答案 0 :(得分:1)
您可以使用带有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
答案 1 :(得分:1)
我想你想要这个:
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;
如果您想要上次激活日期的激活用户列表:
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;
答案 2 :(得分:1)
您可以使用聚合获取最新日期:
select user_id, max(audit_date) as maxad
from user_audits
where isactive = 1
group by user_id;
您可以通过将审核表中的所有信息与上述信息相结合来获取所有信息:
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