简体   繁体   English

SQL同时插入和更新

[英]SQL insert and update in the same time

Hey I have a query that will insert into the table a new data and I want that in the same time update an outher table with the id of the new data that I have entered. 嘿,我有一个查询,它将向表中插入新数据,并且我希望同时用我输入的新数据的ID更新外表。 ex: 例如:

mysql_query("INSERT INTO `test` (`name`) VALUES ('Mark')");
$query = mysql_query("SELECT `id` FROM `test` WHERE `name` = 'Mark'");
$id = mysql_result($query,0);
mysql_quey("UPDATE `test2` SET `test_id` = $id WHERE `name` = 'Mark'");

How do I do it at same time? 如何同时进行? because doing it this way I only insert the new data and I dont update the other. 因为这样做是因为我只会插入新数据,而不会更新其他数据。

Cumps. Cumps。

Try this : 尝试这个 :

mysql_query("INSERT INTO `test` (`name`) VALUES ('Mark')");
$id = mysql_insert_id();
mysql_quey("UPDATE `test2` SET `test_id` = $id WHERE `name` = 'Mark'");

I've changed the backticks to single quotes in your first insert for the values, backticks should never be used for field values. 我已经在您的值的第一个插入中将反引号更改为单引号,绝不应将反引号用于字段值。

Also I've changed it to use only two queries, the mysql_insert_id() will get the last inserted id without you needing to query it. 另外,我将其更改为仅使用两个查询,mysql_insert_id()将获得最后插入的ID,而无需查询它。

Ref : http://www.php.net/manual/en/function.mysql-insert-id.php 参考: http : //www.php.net/manual/zh/function.mysql-insert-id.php

First of all, you do not need the select to get the id, there is mysql_insert_id() for that. 首先,不需要选择即可获取ID,为此有mysql_insert_id()

Then you have to use a transaction to make both queries feel like executed at the same time: 然后,您必须使用事务来使两个查询都感觉像在同时执行:

mysql_query('BEGIN');
mysql_query("INSERT INTO `test` (`name`) VALUES ('Mark')");
$id = mysql_insert_id();
mysql_query("UPDATE `test2` SET `test_id` = $id WHERE `name` = 'Mark'");
mysql_query('COMMIT');

A transaction makes sure both statements are executed, and no other script can come between them in any way. 事务确保两个语句都被执行,并且任何其他脚本都不能以任何方式进入它们之间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM