【发布时间】:2017-06-22 05:50:54
【问题描述】:
我有 2 张桌子。 table1 和 table2
我想将值插入到table1,然后将相同的值复制或插入到table2。
id table1 中的列是 AUTO_INCREMENT 但我不希望 table2 中的 AUTO_INCREMENT 。插入到table1后,只需将id和其他列从table1复制到table2即可
【问题讨论】:
我有 2 张桌子。 table1 和 table2
我想将值插入到table1,然后将相同的值复制或插入到table2。
id table1 中的列是 AUTO_INCREMENT 但我不希望 table2 中的 AUTO_INCREMENT 。插入到table1后,只需将id和其他列从table1复制到table2即可
【问题讨论】:
如果您逐条记录地插入值,则可以在单个事务中进行:
INSERTS INTO table1 (field1,field2...)
VALUES (value1,value2...);
SELECT @max_id:=max(id)
FROM table1;
INSERT INTO table2 (fields...)
VALUES (@max_id, values...);
COMMIT;
【讨论】:
感谢您的回答。但不能正常工作。当 2 表为空并插入值时,表 2 中的 id 为 NULL。在插入第二个值之后,table1 中的 id 为 2,table2 中的 id 为 1
这是我的代码:
$statement = $connection->prepare(
"INSERT INTO users (username, userid, password,type,created)
VALUES (:user_name_post, :shenase_post, :password_post, :userManger_post, NOW())
"
);
$statement->bindParam(":user_name_post",$userName);
$statement->bindParam(":shenase_post",$shenase);
$statement->bindParam(":password_post",$password);
$statement->bindParam(":userManger_post",$usermanager);
$stmt2 = $connection->prepare("SELECT @max_id:=max(id) FROM users");
$stmt2->execute();
$stm1=$connection->prepare("INSERT INTO historyuser (id,username, userid,type,data)
VALUES (@max_id,:user_name_post, :shenase_post,:userManger_post, NOW())");
$stm1->bindParam(":user_name_post",$userName);
$stm1->bindParam(":shenase_post",$shenase);
$stm1->bindParam(":userManger_post",$usermanager);
【讨论】: