简体   繁体   中英

Adding Mysql columns from one table to another

I have two MySQL tables: one called Audit and the other Audit2. I need to copy the column names from Audit2 to Audit. For example table Audit has columns 1, 2 and 3 and Audit2 has columns 4, 5 and 6 and I need Audit to have columns 1, 2, 3, 4, 5 and 6.

I tried the following to no success:

ALTER TABLE  `Audit` ADD  (select `COLUMN_NAME` from information_schema.columns
where table_schema = 'BMS' and `TABLE_NAME` = 'Audit2') (select `DATA_TYPE` from information_schema.columns
where table_schema = 'BMS' and `TABLE_NAME` = 'Audit2') NOT NULL

You can do it by

create table new_audit as
select t1.*,t2.* from audit as t1 inner join audit_2 as t2 on 1=0;

The table new_audit will have all the columns

Have you tried:

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='your_table_name';  

It'll return all the column names in a single column from the table you want.

If you have a PHP environment set up, you can download this tool: http://www.mysqldiff.org/downloads.php It's brilliant - will compare two mysql database schema's and generate the mysql code that will sync the structures together, sounds just like what you need and handy for the future too.

If not. I'd do just what you're doing, but probably just simplify it a bit for the sake of a one off instance and 3 columns.

Something like ALTER TABLE Audit ADD yourcolumnname VARCHAR(100);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM