简体   繁体   中英

combine mutiple tables with different column in to one table

I have three tables that contain totally different data with different header column.

  • table 1) SQL_1 with columns: col_1,col_2,col_3
  • table 2) SQL_2 with columns: col_4,col_5,col_6
  • table 3) SQL_3 with columns: col_7,col_8

I need a query (or a trigger) to insert all these data from these three tables to final_table. I can do these when all tables have the same column, but not with different columns header. Thanks in advance

Could this be as simple as (for a new table)

select *
into new_table
from sql_1, sql_2, sql_3

If you have a table created, then you can populate it with:

insert into new_table (col_1, col_2, col_3, etc.,)
select col_1, col_2, col_3, etc.,
from sql_1, sql_2, sql_3

(adjust the column names to suit)

You could use a UNION statement and aliases:

INSERT INTO final_table
SELECT col_1 AS c1, col_2 AS c2, col_3 AS c3 FROM SQL_1
UNION
SELECT col_4 AS c1, col_5 AS c2, col_6 AS c3 FROM SQL_2
UNION
SELECT col_7 AS c1, col_8 AS c2, NULL AS c3 FROM SQL_3

And choose the column aliases to match the column names in final_table .

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