我有2個表。 table1
和table2
我想將值插入到table1
,之後將相同的值複製或插入到table2
。插入到目標表後將值複製到另一個表中
id
表1中的列是AUTO_INCREMENT
但我不想要AUTO_INCREMENT
在table2
。剛插入後從table1
複製id
和其他列table2
到table1
我有2個表。 table1
和table2
我想將值插入到table1
,之後將相同的值複製或插入到table2
。插入到目標表後將值複製到另一個表中
id
表1中的列是AUTO_INCREMENT
但我不想要AUTO_INCREMENT
在table2
。剛插入後從table1
複製id
和其他列table2
到table1
如果你插入你的價值觀記錄的記錄,你可以把它在一個單一的交易:
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中是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);