In a one-to-many relationship, users
have many contracts
. However, I only want the most recent contract for a specific set of users.
My query to get all contracts for users look like this:
SELECT userid FROM contract
WHERE userid IN (123, 143, 153, 163);
I naively thought the following query could return the most recent contract for the 4 users in the WHERE
clause. However, it only limits to 1 record for the entire result set.
SELECT userid FROM contract
WHERE userid IN (123, 143, 153, 163)
ORDER BY signingdate DESC LIMIT 1 OFFSET 0
How can I fix my query to get the latest records that have a one-to-many relationship?
3
Answers
If you know how to make a subselect or with common table expression query (CTE), then the following will work for you. This numbers the results within each user ID, ordering by the signing date.
This should Work
UPDATE: added DISTINCT to eliminate possibility of duplicates
Rather than
limit and offset
use select distinct on: