2011-03-16 73 views
2

我用相似的标题阅读了这个问题,但它与我的问题不符。mysql复制一些行并更新一列

我有这个表

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,然后更新blah WHERE id = last insert id。但是这是1 + 2个查询。有没有更好的方法,最好是一个查询?

回答

4

如果你已经知道了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>爪牙,然后将最终结果集到Robot_minions<new robot_master_id>

相关问题