I have the following tables:
matrices
- a matrix name and some other metadata.matrix_values
- stores various data points of a 2D matrix as a JSON value column (Postgres). Also the FK matrix_id for a belongs-to association.products
- amatrix_value
may be joined to aproduct
via join tablematrix_value_products
matrix_values
MAY be associated with only oneproduct
, but are not required to be; in fact, most aren't. Which is why is used a join table instead of a belongs-to FK relationship to avoid having mostly NULL values in a FK column
ERD looks like
Each matrix has several matrix_values
where either A) none of them are associated with a product
, or B) all of them are associated with a product (possibly different products).
In scenario A, the multiple records are a history of the 2D matrix, where the most recently created record is the current representation. This scenario is easy for me to find the most recent matrix_value
.
How can I create a query for scenario B in order to find the most recent matrix_values
record per product? For matrix 777 below, I want to return matrix_values
records 2 (most recent for product P) and 4 (most recent for product Q).