I have the following structure (simplified for brevity). I am mostly frontend developer that suddenly needs to learn the basics of SQL, so bear with me, please :)
CREATE TABLE user (
id text NOT NULL,
lastOnlineAt timestamptz NOT NULL
);
CREATE TABLE pair (
id text NOT NULL
);
CREATE TABLE userPair (
userId text NOT NULL,
pairId text NOT NULL
);
The important aspect here is that every pair
is linked to exactly 2 user
entities (through userPair
). I am not sure if was the wisest approach, but I did not like the idea of having columns user1/2
inside the pair
.
Now I need to do a SELECT that for every user
finds associated pair
s, picks the other user
of that pair
and gets his lastOnlineAt
for a comparison. Effectively I need to find paired users that were online in the last 5 minutes.
I would probably start like this.
SELECT up.'pairId'
FROM 'userPair' AS up
LEFT JOIN pair as p
WHERE up.'userId' = $userId
AND p.id = up.'pairId'
But then I am getting lost in complexity here.
It's for the Postgres 12.