I feel there is a simple solution to this — I’ve looked at other questions on Stack Overflow, but they seem to be inefficient, or perhaps I’m doing them wrong.
Here are simplified versions of tables I’m working with.
CREATE TABLE object_values (
object_value_id INT PRIMARY KEY,
object_id INT,
value FLOAT,
date_time DATETIME,
INDEX (object_id)
);
CREATE TABLE object_relations (
object_group_id INT,
object_id INT,
INDEX (object_group_id, object_id)
);
There is a many-to-one relationship — many object values per one object (150 object values on average per object)
I want to get the last object value (determined by date_time field) for each object_id based on the object_group_id.
Current Query:
SELECT a.`object_id`, a.`value`
FROM `object_values` AS a
LEFT JOIN `object_relations` AS b
ON ( a.`object_id` = b.`object_id` )
WHERE b.`object_group_id` = 105
ORDER BY a.`date_time` DESC
This pulls back all the records — if I do a GROUP BY a.object_id then the ORDER BY gets ignored
I have tried a series of variations — and I apologize as I know this is a common question, but trying the other solutions hasn’t quite worked so far. Any help would greatly appreciated.
Some of the solutions came back with results about 70 seconds later — this is a large system so needs to be a bit faster.
You can omit the final
GROUP BYif there will never be duplicatedate_timein a single group.