I am totally stumped on what seems like a simple problem. Maybe I'm just confused because I've been thinking/googling/searching around about it 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)
Executing the following select:
SELECT *
FROM logs
WHERE domain_id = 4
Would give me, say, 2 logs of the type 'notice' and 3 of the type 'warning'.
How would I go about selecting only the logs with the highest ID of their type
? Effectively giving me the latest log per domain_id
and type
.
Just describing it makes me feel stupid, but I can't seem to get it right..
Thanks for your help.
Chris
Edit: For future reference, in case you want to select all records from the first table and show the latest record of the joined table (in this case select all domains and their latest log record (if available)), simply wrap a select on the domains table 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)
Join to a subquery first:
select
l.*
from
log l
inner join (
select
max(log_id) as maxid
from
log
group by
domain_id,
type
) l2 on
l.log_id = l2.maxid
What you need is a GROUP BY, like this query below:
SELECT `type`, MAX(`log_id`) AS `latest_log`
FROM `logs`
WHERE `domain_id` = 4
GROUP BY `type`;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With