首页 文章

mysql复制一些行并更新一列

提问于
浏览
2

我读了一个类似 Headers 的问题,但它与我的问题不符 .

我有这张 table

Robot_Minions
id | type   | id_robot_master
1  | catbot | 15
2  | dogbot | 15
3  | batbot | 15

我想要做的是复制Robot_Master 15的所有Robot_Minons并将它们分配给Robot_Master 16 .

所以最终的结果应该是这样的

Robot_Minions
id | type   | id_robot_master
1  | catbot | 15
2  | dogbot | 15
3  | batbot | 15
4  | catbot | 16
5  | dogbot | 16
6  | batbot | 16

我能想到的一种方法是首先选择要复制的行,然后循环遍历它们并运行INSERT blah然后UPDATE blah WHERE id = last insert id . 但这是1次2次查询 . 有没有更好的方法,理想情况下作为一个查询?

1 回答

  • 4

    如果你已经知道你想将minions分配给你的robot_master的id,你可以使用以下查询:

    INSERT INTO Robot_minions (type,id_robot_master)
    SELECT type, '<new robot_master_id>' 
    FROM Robot_minions
    WHERE id_robot_master = '<old robot_master>'
    

    这将选择属于 <old robot_master> 的minions,然后使用 <new robot_master_id> 将最终结果集插入 Robot_minions

相关问题