Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select highest record of type per foreign key

Tags:

sql

mysql

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)
like image 698
Christof Avatar asked Feb 22 '23 21:02

Christof


2 Answers

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
like image 195
Eric Avatar answered Feb 24 '23 10:02

Eric


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`;
like image 24
Abhay Avatar answered Feb 24 '23 11:02

Abhay