So, I have 2 tables.
Table: Measuremements
PersonID - Value - Timestamp - TypeID
Table: Measurement type
TypeID - Measurement Name
I want to display the 2 most recent entries from 2 different TypeIDs. So I need to select one Value from TypeID 1 with the most recent timestamp and one Value from TypeID 2 with the most recent timestamp. I also have to get the names of the measurements using the TypeID between the tables. And I want to limit my selection to a specific PersonID.
I have tried different ways to do this, but I just don't understand what to do.
At the moment my code is:
SELECT
m.value,
m.timestamp,
m_t.measurement_name
FROM measurements m
INNER JOIN measurement_type m_t ON m.typeid = m_t.typeid
GROUP BY m.typeid
ORDER BY timestamp DESC
My first question, so I can try to explain it better if needed :D
You can use a subquery to get the max
timestamp for each type and then join
the result back to itself:
select m.typeid, m.value, m.timestamp, mt.measurement_name
from measurements m
join (select max(timestamp) maxtimestamp, typeid
from measurements
group by typeid) m2 on m.timestamp = m2.maxtimestamp
and m.typeid = m2.typeid
join measurement_type mt on m.typeid = mt.typeid
You can use the following query to get the most recent entry for given type id:
select m.personID, m.value, m.typeID, mt.measurement_name
from measurements m join measurements_type mt on m.typeID = mt.typeID
where m.typeID = ?
order by m.timestamp desc limit 1;