开发者

SQL - Copy row from one table to another and update column in destination table at the same time

I have 2 tables like below structure. Both are id开发者_如何学JAVAentical except of table name.

tbl_item_color_exp
>>item_color_ID
>>color_ID
>>item_ID

tbl_item_color_live
>>item_color_ID
>>color_ID
>>item_ID

I wished to copy several rows from tbl_item_color_live table to tbl_item_color_exp table. I can accomplished copying the exact column and row by the following SQL below:

INSERT INTO tbl_item_color_exp 
SELECT * FROM tbl_item_color_live WHERE item_ID = $oldID

But I don't want to create replicate item_color_ID primary key and I want to update all rows copied's item_ID column to a new variable, $newID. The general idea is copy all rows based on $oldID and update destination table with &newID but maintaining color_ID column with a auto incremented primary key item_color_ID.

I can accomplish it using several SQL queries but I was wondering if it is possible for me to do everything in more efficient manner by just one SQL line? I hope my question can be understandable by all, thank you.


I'm not 100% sure I understand what you want, but it sounds like you only actually want to copy the color_ids, you want to set them all with a new item_id, and you want autonumbering to occur.

Sounds like:

INSERT INTO tbl_item_color_exp (color_id,item_id)
SELECT color_id,$newID FROM tbl_item_color_live WHERE item_ID = $oldID


INSERT INTO tbl_item_color_live (color_ID, item_ID)
SELECT color_ID, $newID FROM tbl_item_color_exp WHERE item_ID = $oldID
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜