示例我具有带有字段(home_id,home_name)的临时表1(Home_Temp),并包含数据。我想将所有数据从表1插入表2(Home_History)。表2包含字段(home_id,home_name,状态)。 “状态”的默认值为1。Home_Temp的主键为home_id
,而Home_History的主键为home_id
和status
。
对于第一次插入过程,可以将数据从表1插入到表2,并且'status'的默认值为1。对于具有相同home_id的第二次插入过程,我想将home_name和status插入为'1' 。但是我想将具有相同home_id和home_name的旧数据更新为状态“ 0”。意味着最新的home_id的状态值为“ 1”。旧的home_id的状态值为“ 0”。该代码将成功,直到将旧home_id的状态更新为“ 0”为止。
$stmt = $dbcon->prepare("INSERT INTO Home_History (home_id, home_name) SELECT home_id, home_name FROM Home_Temp ON DUPLICATE KEY UPDATE status = '0'");
$stmt->execute();
但是如何插入最新数据?我尝试在下面执行代码,但似乎胡说八道且无法正常工作。
$stmt = $dbcon->prepare("INSERT INTO Home_History (home_id, home_name) SELECT home_id, home_name FROM Home_Temp ON DUPLICATE KEY UPDATE status = '0' AND INSERT INTO Home_History (home_id, home_name) SELECT home_id, home_name FROM Home_Temp");
$stmt->execute();
对于执行两个查询,您不能使用“ AND”,但使用此代码:
$sql = "
INSERT INTO Home_History (home_id, home_name) SELECT home_id, home_name FROM
Home_Temp ON DUPLICATE KEY UPDATE status = '0';
INSERT INTO Home_History (home_id, home_name) SELECT home_id, home_name FROM
Home_Temp;
";
try {
$stmt = $db->prepare($sql);
$stmt->execute();
}
听起来,您想要在插入后将Home_History中添加的home_id / home_name值的状态设为1,将无法添加的home_id / home_name的值设为状态0。为此,您需要在[C0 ],而不是(home_id, home_name)
。