Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

specific mysql update based on group by data

This one has me stumpped.

I have 2 tables as so:

METERS
id | startTime

READINGS
id | meter_id | readingTime

What I want to do is update the meters.startTime to the lowest matching readings.readingTime in 1 sql query.

How do I do this?

like image 518
khany Avatar asked Dec 05 '22 13:12

khany


2 Answers

Like this:

UPDATE Meters m
INNER JOIN
(
   SELECT meter_id, MIN(reading_time) lowesttime
   FROM readings 
   GROUP BY meter_id
) r ON m.id = r.meter_id
SET m.starttime = r.lowesttime;
like image 179
Mahmoud Gamal Avatar answered Dec 08 '22 05:12

Mahmoud Gamal


UPDATE METERS m SET startTime = (SELECT MIN(r.readingTime)
    FROM READINGS r
    WHERE r.meter_id = m.id)
WHERE m.id = your_id
like image 29
xlecoustillier Avatar answered Dec 08 '22 04:12

xlecoustillier