我们可以用单个sql语句插入两个表吗?

时间:2022-06-24 14:32:59

Will it be possible to insert into two tables with same insert command?

是否可以使用相同的insert命令插入两个表中?

4 个解决方案

#1


9  

No you cannot perform multiple inserts into two tables in one query.

不,您不能在一个查询中对两个表执行多次插入。

#2


4  

No you can't.

不,你不能。

If you want to ensure the atomicity of an operation that requires data to be inserted into 2 tables, you should protect it in a transaction. You either use the SQL statements BEGIN TRAN and COMMIT TRAN, or you use a transaction boundary in whatever language you're using to develop the db access layer. E.g. something like Connection.StartTransaction and Connection.Commit (or Connection.Rollback on an error).

如果要确保需要将数据插入2个表的操作的原子性,则应在事务中保护它。您可以使用SQL语句BEGIN TRAN和COMMIT TRAN,也可以使用您用于开发数据库访问层的任何语言的事务边界。例如。像Connection.StartTransaction和Connection.Commit(或错误的Connection.Rollback)之类的东西。

#3


2  

You can call a stored procedure with inserts into two tables.

您可以通过插入两个表来调用存储过程。

#4


2  

Maybe in a future release of MySQL you could create a View containing the 2 tables and insert into that.
But with MySQL 5.1.41 you'll get the error:
"Can not modify more than one base table through a join view"

也许在将来的MySQL版本中,您可以创建一个包含2个表的View并插入其中。但是使用MySQL 5.1.41,您将收到错误:“无法通过连接视图修改多个基表”

But inserting into 2 tables with 1 query is a weird thing to do, and I don't recommend it.

但是使用1个查询插入2个表是一件很奇怪的事情,我不推荐它。


For more on updatable views check out the MySQL reference.

有关可更新视图的更多信息,请查看MySQL参考。

#1


9  

No you cannot perform multiple inserts into two tables in one query.

不,您不能在一个查询中对两个表执行多次插入。

#2


4  

No you can't.

不,你不能。

If you want to ensure the atomicity of an operation that requires data to be inserted into 2 tables, you should protect it in a transaction. You either use the SQL statements BEGIN TRAN and COMMIT TRAN, or you use a transaction boundary in whatever language you're using to develop the db access layer. E.g. something like Connection.StartTransaction and Connection.Commit (or Connection.Rollback on an error).

如果要确保需要将数据插入2个表的操作的原子性,则应在事务中保护它。您可以使用SQL语句BEGIN TRAN和COMMIT TRAN,也可以使用您用于开发数据库访问层的任何语言的事务边界。例如。像Connection.StartTransaction和Connection.Commit(或错误的Connection.Rollback)之类的东西。

#3


2  

You can call a stored procedure with inserts into two tables.

您可以通过插入两个表来调用存储过程。

#4


2  

Maybe in a future release of MySQL you could create a View containing the 2 tables and insert into that.
But with MySQL 5.1.41 you'll get the error:
"Can not modify more than one base table through a join view"

也许在将来的MySQL版本中,您可以创建一个包含2个表的View并插入其中。但是使用MySQL 5.1.41,您将收到错误:“无法通过连接视图修改多个基表”

But inserting into 2 tables with 1 query is a weird thing to do, and I don't recommend it.

但是使用1个查询插入2个表是一件很奇怪的事情,我不推荐它。


For more on updatable views check out the MySQL reference.

有关可更新视图的更多信息,请查看MySQL参考。