Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
760 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...