如何在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
- 使用事务来确保两个插入都成功或两个都回滚了.
- 创建同时执行两次插入的存储过程.
希望这会有所帮助