我可以在 INSERT 语句中使用子查询吗?
我需要在表中插入一行,其中一个字段值是从另一个表中计算出来的.与其进行两次查询并冒着竞争条件的风险,我认为最好在一个语句中完成所有操作.
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?
推荐答案
INSERT INTO `myTable` (`someData`, `averageAtThisTime`)
select "some stuff", AVG(`myField`)
FROM `myOtherTable`
相关文章