specific mysql update based on group by data

2020-02-14 06:53发布

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?

2条回答
Luminary・发光体
2楼-- · 2020-02-14 07:26

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;
查看更多
我命由我不由天
3楼-- · 2020-02-14 07:35
UPDATE METERS m SET startTime = (SELECT MIN(r.readingTime)
    FROM READINGS r
    WHERE r.meter_id = m.id)
WHERE m.id = your_id
查看更多
登录 后发表回答