Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy some data from sqlite table to the same table with different two columns

Tags:

sqlite

copy

Let say I have table T with columns A,B,C,D,E,F
A is autoincrement primary key
I have there some data
I want to copy all data where B=x
I want to copy data to the same table but while copying set A to null (so it can create new IDs) and change B to y.
Example:

A,B,C,D,E,F  
1,1,9,8,3,9 
2,1,0,3,2,2 
3,1,7,1,1,8 
4,2,5,4,7,5 
5,2,6,5,8,4 
6,3,9,4,5,3 


 x = 2, y = 4  


Result:

A,B,C,D,E,F 
1,1,9,8,3,9  
2,1,0,3,2,2 
3,1,7,1,1,8 
4,2,5,4,7,5 
5,2,6,5,8,4 
6,3,9,4,5,3 
7,4,5,4,7,5  
8,4,6,5,8,4  

I found one solution
Create table Temp as select * from T where B = x
Then
Update T set A = null, B = y
Then Insert into T select * from Temp
Then drop table temp

I didn't test but it should work, but is there easier way or can it be written in one single query?

like image 449
Radosław Malinowski Avatar asked May 26 '26 00:05

Radosław Malinowski


1 Answers

I found solution, maybe not the best but quite good:

INSERT INTO T (A,B,C,D,E,F) SELECT null,y,C,D,E,F from T WHERE B = x
like image 200
Radosław Malinowski Avatar answered May 28 '26 07:05

Radosław Malinowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!