[英]How to find a last record for a record in first table in mysql
我有一個用戶的第一張表,其中有一個布爾字段來表示用戶為active
用戶,在第二張表中,我有用戶audits
。
我必須要找到當用戶啟動一次,這樣就意味着我有很多數量的audits
只需要最后得到激活audit
為當前active
用戶。
用戶表字段:
user_id, username, firstname, lastname, email, isactive
審核表字段:
user_id, audit_date, actiontype
您可以將臨時表與最大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
我想你想要這個:
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;
您可以使用匯總來獲取最新日期:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.