2011-03-16 47 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>

相關問題