Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT INTO SELECT - Change a value

Tags:

mysql

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.

enter image description here

Code:

INSERT INTO table2 SELECT * FROM table1 WHERE volume = 'Story of a Girl
like image 684
code Avatar asked Jan 08 '18 16:01

code


2 Answers

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;
like image 152
smcjones Avatar answered Sep 18 '22 22:09

smcjones


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')... 
like image 24
Hesy Ra Avatar answered Sep 21 '22 22:09

Hesy Ra