簡體   English   中英

從一個MySQL表復制到另一個MySQL表的問題

[英]Issue with copying from one MySQL table to another

我正在嘗試從一個表復制到另一表,並且工作正常,但是我還需要在新表中插入當前用戶ID。 我還沒弄清楚怎么做。 通常我會做類似SET user_id = :user_id事情,但是我從來沒有使用過這個。

這是我的代碼:

$q = $conn->prepare("INSERT INTO user_themes(title,code_entry,code_home,code_css,code_category,code_archive)
    SELECT title, code_entry, code_home, code_css, code_category, code_archive FROM blogy_themes WHERE id = :id");

所以我的問題是:如何將user_id (假設user_id為1)也插入到新表中?

您查詢的依據不會改變。 只需將值添加到列和`SELECT語句中:

INSERT INTO user_themes(user_id, title,code_entry,code_home,code_css,code_category,code_archive)
  SELECT :user_id, title, code_entry, code_home, code_css, code_category, code_archive
    FROM blogy_themes WHERE id = :id

然后在執行時,同時綁定:id:user_id

據我了解,您希望在所有新記錄中都具有正在執行操作的用戶的ID,您可以執行以下操作:

$q = $conn->prepare("INSERT INTO user_themes(user_id,title,code_entry,code_home,code_css,code_category,code_archive)
SELECT '" . (int) $userid ."' as user_id, title, code_entry, code_home, code_css, code_category, code_archive FROM blogy_themes WHERE id = :id");

這是一種解決方法,可以繼續按原樣使用查詢。 第二種選擇是更多的“ ORM”方法,您可以從user_themes表中查詢所有相關記錄,對結果集進行迭代,克隆每一行並用新的user_id保存。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM