开发者

mysql copy some rows and update one column

i read the question with a similar title but it doesn't match my problem.

I have this table

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

What I want 开发者_StackOverflow社区to do is copy all the Robot_Minons of Robot_Master 15 and assign them to Robot_Master 16.

So the end result should look like

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

One way I can think of to do it is to first select the rows to be copied, then loop through them and run an INSERT blah then UPDATE blah WHERE id=last insert id. But this is 1+2x queries. Is there a better way, ideally as one query?


if you already know the id of the robot_master you wish to assign the minions to you can use the following query:

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

this will select the minions that belong to the <old robot_master> and then insert the end resultset into Robot_minions with the <new robot_master_id>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜