I have to write a reporting query for a kind of versioning system where I need to retrieve date-based reporting variations of the latest version. Simplified table structures are:
items_register: ir_id (primary, auto inc), ir_name (varchar)
items: i_id (primary, auto inc), i_register_id (int), i_version_name (varchar), i_datetime (datetime), i_date_expiry (datetime)
Each entry in items_register has multiple associated versions, stored as entries in the items table – with the highest value of i_datetime being the most recent version.
I want to retrieve entries from the items_register where the most recent version (item) has i_date_expiry after a requested date ($f_date).
I think I somehow need to join the tables, order the items by i_datetime, limit them to 1 so I get the most recent version, then check if i_date_expiry is after $f_date & retrieve the fields if so.
The fields I want to retrieve are items_register.ir_id, items_register.ir_name, items.i_version_name, items.i_datetime.
TIA for any help.
It looks like you’re searching for the “groupwise max” pattern.
Making a few assumptions about things that still aren’t clear in your question, I think this may be the query you’re looking for:
Bear in mind that this assumes that $f_date is a string that conforms to the standards for datetime and timestamp literals (not date literals!) laid out in this documentation page.