Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

Tags:

mysql

I have two tables with identical structure except for one column... Table 2 has an additional column in which I would insert the CURRENT_DATE()

I would like to copy all the values from table1 to table2.

If I use

INSERT INTO dues_storage SELECT * FROM dues WHERE id=5; 

it throws an error pointing to the difference in the number of columns.

I have two questions:

  1. How do I get around this?
  2. How do I add the value for the additional date column (CURRENT_DATE()) in table2 within this same statement?
like image 256
user165242 Avatar asked Aug 30 '09 11:08

user165242


People also ask

How do I copy rows from one table to another in MySQL?

SET @sql = CONCAT( 'INSERT INTO <table_name> (', ( SELECT GROUP_CONCAT( CONCAT('`',COLUMN_NAME,'`') ) FROM information_schema.


2 Answers

To refine the answer from Zed, and to answer your comment:

INSERT INTO dues_storage SELECT d.*, CURRENT_DATE() FROM dues d WHERE id = 5; 

See T.J. Crowder's comment

like image 200
crunchdog Avatar answered Sep 30 '22 06:09

crunchdog


The safest way to do it is to fully specify the columns both for insertion and extraction. There's no guarantee (to the application) that either of these will be the order you think they may be.

insert into dues_storage (f1, f2, f3, cd)     select f1, f2, f3, current_date() from dues where id = 5; 

If you're worried about having to change many multiple PHP pages that do this (as you seem to indicate in the comment to another answer), this is ripe for a stored procedure. That way, all your PHP pages simply call the stored procedure with (for example) just the ID to copy and it controls the actual copy process. That way, there's only one place where you need to maintain the code, and, in my opinion, the DBMS is the right place to do it.

like image 45
paxdiablo Avatar answered Sep 30 '22 06:09

paxdiablo