简体   繁体   中英

Getting highest column value from joined table

Having a bit of trouble understanding all but the most basic joining concepts. The diagrams don't help much.

I've got three tables I want to join:

  • environments,
  • sessions, and
  • logs

Here's some screenshots of the tables.

Environments:

环境环境

Sessions:

届会

Logs:

日志

I want to select columns environments.envCode and logs.type. What I want is to get the logs.type from the last log for each environment. Environments and logs are related through session by environments.envCode in sessions and sessions.sessionID in logs.

I've tried several ways of querying this but just can't seem to get it right. This is one of the ways I've tried to do it:

 SELECT environments.envCode
        ,logs.type 
        FROM environments
        LEFT JOIN session
        ON environments.envCode = session.envCode
        LEFT JOIN logs
        ON session.sessionID = logs.sessionID
        WHERE logs.logID = (SELECT MAX(logID) FROM logs);

What I'm getting now is one result, for only the row with the highest logID from logs. Makes sense, I understand why it's not giving me the results I'm looking for, but I'm still not sure how to go about getting the results I want.

You want only those result records where no later log entry EXISTS for the environment:

select 
  environments.envcode,
  logs.type 
from environments
left join session on environments.envcode = session.envcode
left join logs on session.sessionid = logs.sessionid
where not exists
(
  select *
  from sessions later_session
  join logs later_log on later_log.sessionid = later_session.sessionid
  where later_session.envcode = session.envcode
  and later_log.created > logs.created
);

EDIT: I changed above query so that the latest logs, not the latest sessions, get selected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM