Reputation: 837
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:
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.
Upvotes: 0
Views: 56
Reputation: 94914
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.
Upvotes: 2