I am completely obsessed with what seems like a simple problem. Maybe I'm just embarrassed because I thought / searched / searched around for too long.
Consider the following table:
log_id (auto increment primary key) domain_id (foreign key to "domains" table) type (enum('notice','warning')) message (varchar)
Making the following selection:
SELECT * FROM logs WHERE domain_id = 4
Would give me, say, 2 logs of the type "notification" and 3 types of "warning".
How can I select only the logs with the highest identifier of their type ? Effectively giving me the last log for domain_id and type .
Just describing it, I feel stupid, but I canโt understand that itโs right.
Thank you for your help.
Chris
Edit: For future reference, if you want to select all the records from the first table and show the last record of the joined table (in this case, select all the domains and their last log entry (if any)), simply wrap the table in the domains around it:
SELECT domains.*, logs.* FROM domains LEFT JOIN ( SELECT l.* FROM logs l INNER JOIN ( SELECT MAX(log_id) as maxid FROM logs GROUP BY domain_id type ) l3 ON l.log_id = l3.maxid ) l2 USING (domain_id)
source share