![](/img/trans.png)
[英]how to update a table and insert a new record to another table in one query?
[英]Query for insert one record (ID) from one table to another table
請幫我查詢mysql...
我有這種情況:
表1 -- -- 任務
**id**|task_name|status|created_at|updated_at|user_id
和表 2 -- 樣品
id|sample_name|...|...|...many other things|**task_id**|user_id
我希望表 2 中的“task_id”列是表 1 中的“id”或“tasks.id”?
我有這個查詢,但它的結果是每列中的數字 1 而不是每個條目的 id..
INSERT INTO samples(task_id),
SELECT tasks.id from tasks
JOIN samples
ON task_id = tasks.id
感謝幫助...
假設您是通過 PHP 執行此操作(基於您對其進行標記)並假設您需要插入到兩個表中,那么基本的 jist 將是(還假設任務中的 id 字段是自動遞增的):
$stmt1 = $conn->prepare("INSERT INTO tasks (fields, other_fields) VALUES (?, ?)"))
{
$stmt1->bind_param("ss",$fields, $other_fields);
$stmt1->execute();
$lastid = $conn->insert_id;
$stmt1->close();
}
現在,您可以在插入示例數據時使用變量 $lastid 作為值。
$stmt2 = $conn->prepare("INSERT INTO samples (id, other_fields, task_id) VALUES (?, ?, /)"))
{
$stmt2->bind_param("isi",$ID, $other_fields, $lastid);
$stmt2->execute();
$stmt2->close();
}
如果樣本已經存在並且您需要使用任務中的 id 更新它,那么您只需在插入任務后更新樣本,假設您在 where 子句中可以使用可以唯一標識要更新的記錄的內容:
$stmt2 = $conn->prepare("UPDATE samples set task_id = ? where user_id - ?)
$stmt2->bind_param("ii",$lastid, $user_id);
$stmt2->execute();
$stmt2->close();
}
else {
die(mysqli_error($conn));
}
我做了很多假設,我知道。 但我還不能發表評論,所以這是我唯一的協助方式。
不幸的是,您的方法不正確且不合邏輯。 在你記錄的那一刻,沒有可以統一表數據的字段,所以你需要先獲取task_id ,然后將其插入到查詢中
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.