How would I change a value of a column when using the INSERT INTO SELECT which copies data from one table and inserts it into another table. See example (pic below)
I'm trying to copy data from one (main) table to another table but update a value on 2nd table.
Code:
INSERT INTO table2 SELECT * FROM table1 WHERE volume = 'Story of a Girl
INSERT INTO table2 (username, volume, name, image, content, cssanimate)
SELECT 'tim', volume, name, image, content, cssanimate
FROM table1 where volume='Story of a Girl';
If you list the columns you want to insert, you can replace columns with custom values.
You can get more complex too:
INSERT INTO table2 (username, volume, name, image, content, cssanimate)
SELECT
CASE
WHEN 'admin' THEN 'tim'
ELSE username
END CASE,
volume, name, image, content, cssanimate
FROM table1;
You can also modify columns at insert by using
INSERT INTO ...() SELECT ...REPLACE(fieldname, 'somestring','anotherstring') ...
Or even use a subquery
INSERT INTO ...() SELECT ...(SELECT id FROM tableName WHERE somefield = 'asd')...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With