Saturday, August 11, 2018

sql - How to copy a row and insert in same table with a autoincrement field in MySQL?



I have a table Eg- tab . What I am trying to do is copying a row with an autoincrement column ID=1 and insert the data into same table with a row and column ID=2.



Using MySql.
How can I do this in a single query?Please help



Answer



Use INSERT ... SELECT:



insert into your_table (c1, c2, ...)
select c1, c2, ...
from your_table
where id = 1


where c1, c2, ... are all the columns except id. If you want to explicitly insert with an id of 2 then include that in your INSERT column list and your SELECT:




insert into your_table (id, c1, c2, ...)
select 2, c1, c2, ...
from your_table
where id = 1


You'll have to take care of a possible duplicate id of 2 in the second case of course.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...