Fashion

SQL Query of 3 tables (one of which is a junction)

I am attempting to build a query that will grab values from 2 tables that are related through a junction table. I’ve included a screenshot of the tables in question. (apparently cannot embed pictures yet, first post!)

https://i.stack.imgur.com/Ru9qJ.png

In my query I need all the fields from worker and the NEWEST LMIA.lmia_number. The issue I am running into is whenever I include lmia_number in the query, workers that are in more than one LMIA relation, the worker info show up as duplicates and the LMIA fields are different. I’ve included one of the queries where I feel I was the closest to getting it Ex:

SELECT DISTINCT
worker.worker_id,
LMIA.lmia_id,
LMIA.lmia_number,
LMIA.date_created
FROM LMIA

INNER JOIN worker_lmia
    ON worker_lmia.lmia_id = LMIA.lmia_id
INNER JOIN worker
    ON worker.worker_id = worker_lmia.worker_id
INNER JOIN (SELECT lmia_id, MAX (date_created) as maxDate
    FROM LMIA
    GROUP BY lmia_id
    ) ij ON worker_lmia.lmia_id = ij.lmia_id AND LMIA.date_created = ij.maxDate

This returns: https://i.stack.imgur.com/JBT1s.png

Where my goal is to retrieve 1 row per worker with most recent lmia_number and date_created (using lmia.date_created).

Any help would be greatly appreciated!