Can I use a subquery inside an INSERT statement?(我可以在 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`
这篇关于我可以在 INSERT 语句中使用子查询吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以在 INSERT 语句中使用子查询吗?
基础教程推荐
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 在多列上分布任意行 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
