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

I need to insert a row into a table, with one field value being calculated from another table. Rather than doing two queries and risking a race condition, I thought it'd be better to do it all in one statement.

INSERT INTO `myTable` (`someData`, `averageAtThisTime`)
VALUES (
    "some stuff",
    SELECT AVG(`myField`) FROM `myOtherTable`
)

... but this doesn't work. Is there a way I can achieve this in one statement? If not, what's your recommendation?

See Question&Answers more detail:os

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

1 Answer

INSERT INTO `myTable` (`someData`, `averageAtThisTime`)
select "some stuff", AVG(`myField`) 
FROM `myOtherTable`

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