繁体   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