Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting from a SELECT but changing one column?

Tags:

sql

Wondering if there is a way to insert a row into a table from another, with exception of one column?

This is of course easy with a limitied amount of columns, but gets kind of tiredsome listing all of the columns when the number of columns increases.

I'm thinking something in the line of:

Insert into table select * replace col1 with current date from table where yada yada yada 

One possiblilty would be to duplicate one row and perform and update, but let's say that's not an option due to an index or something.

Any ideas?

Edit: It's DB2 v10, but the question is out of pure curiousity. Just wondering if it is possible...

like image 805
bek Avatar asked Apr 12 '13 13:04

bek


People also ask

How do you exclude a column from a selection statement?

COLUMNS table holds all information about the columns in your MySQL tables. To exclude columns, you use the REPLACE() and GROUP_CONCAT() functions to generate the column names you wish to include in your SELECT statement later.

Is it possible to only insert data in specific columns?

It is also possible to only insert data in specific columns.

Can we use insert and select together?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.


1 Answers

You can use temporary tables

Create Temporary table

CREATE TEMPORARY TABLE temp_table AS (SELECT * FROM MyTable WHERE ...); 

Update column

UPDATE temp_table SET column='Value' WHERE ...; 

Or drop a column

ALTER TABLE temp_table DROP column_name; 

Insert to destination table

INSERT INTO MyDestinationTable SELECT * FROM temp_table; 
like image 200
taari Avatar answered Sep 18 '22 21:09

taari