如何在MySQL的两个表中插入相同的数据 [英] How to insert same data into two tables in mysql

查看:310
本文介绍了如何在MySQL的两个表中插入相同的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想同时向两个表中插入一些数据,这可能吗? 但是在table2处,我只是插入选定的项目,而不是像table1那样插入所有数据. 这是单独的查询:

Is this possible if I want to insert some data into two tables simultaneously? But at table2 I'm just insert selected item, not like table1 which insert all data. This the separate query:

$sql = "INSERT INTO table1(model, serial, date, time, qty) VALUES ('star', '0001', '2010-08-23', '13:49:02', '10')";   

$sql2 = "INSERT INTO table2(model, date, qty) VALUES ('star', '2010-008-23', '10')";   

我可以在表2上插入COUNT(model)吗? 我找到了一些脚本,可以使用吗?

Can I insert COUNT(model) at table2? I have found some script, could I use this?

$sql = "INSERT INTO table1(model, serial, date, time, qty) VALUES ('star', '0001', '2010-08-23', '13:49:02', '10')";
$result = mysql_query($sql,$conn);
if(isset($model))
{
  $model = mysql_insert_id($conn);
  $sql2 = "INSERT INTO table2(model, date, qty) VALUES ('star', '2010-008-23', '10')";   
  $result = mysql_query($sql,$conn);
}
mysql_free_result($result);

推荐答案

简单的答案是否定的-无法通过一条命令将数据插入到两个表中.可以肯定,您的第二个脚本不是您想要的.

The simple answer is no - there is no way to insert data into two tables in one command. Pretty sure your second chuck of script is not what you are looking for.

通常情况下,此类问题可以通过以下一种方法解决,具体取决于您的实际需求:

Generally problems like this are solved by ONE of these methods depending on your exact need:

  • 创建一个表示第二张表的视图
  • 创建触发器以将其插入到table2
  • 使用事务来确保两个插入都成功或两个都回滚了.
  • 创建同时执行两次插入的存储过程.

希望这会有所帮助

这篇关于如何在MySQL的两个表中插入相同的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆