I have this query which is supposed to find the latest uploaded pids and reps of a user. The query looks like this:
SELECT usr.id, up.*,
(SELECT COALESCE(state, 'processing') AS pidState FROM PID WHERE userId = usr.id ORDER BY createdAt DESC LIMIT 1),
(SELECT COALESCE(state, 'processing') AS repState FROM REP WHERE userId = usr.id ORDER BY createdAt DESC LIMIT 1),
(SELECT createdAt AS pidCreatedAt FROM PID WHERE userId = usr.id ORDER BY createdAt DESC LIMIT 1),
(SELECT createdAt AS repCreatedAt FROM REP WHERE userId = usr.id ORDER BY createdAt DESC LIMIT 1)
FROM User AS usr
JOIN UserProfile AS up ON up.userId = usr.id
ORDER BY pidCreatedAt DESC NULLS LAST, repCreatedAt DESC NULLS LAST
I tried joining PID and REP to the User but that gave me a load of returned rows since I only want the latest from each. Now I also have the need to return the PID and REP id fields, which would result in another subquery, so I am wondering if there's a smarter way to solve this other than to keep on writing sub queries for every column that I need in the future?
APPLYorLATERALwould probably help here, but see https://dba.stackexchange.com/questions/86415/retrieving-n-rows-per-group – Charlieface Jul 16 '21 at 15:56useris a reserved word, which would raise an exception when used as table name like this. Please provide your actual query, and be clear whether it produces desired results. Also your version of Postgres and table definitions (CREATE TABLEstatements). – Erwin Brandstetter Jul 17 '21 at 00:37