Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating one Table from three different Tables

I have three tables in SQL and I need them to all be combined into one. I need all the fields from all the tables in the one table. All the tables contain the same fields just from three different years. I wrote a code that is:

CREATE TABLE COL_TBL_TRAINING_ALL_YEARS AS(
SELECT 
COL_TBL_2010_TRN_RESULTS_new.*,
COL_TBL_TRN_RESULTS_GEMS_2011.*, 
COL_TBL_TRN_RESULTS_GEMS_2012.*
FROM COL_TBL_2010_TRN_RESULTS_new,
COL_TBL_TRN_RESULTS_GEMS_2011, 
COL_TBL_TRN_RESULTS_GEMS_2012
WHERE COL_TBL_2010_TRN_RESULTS_new.SYS_EMP_ID_NR = COL_TBL_TRN_RESULTS_GEMS_2011.SYS_EMP_ID_NR = COL_TBL_TRN_RESULTS_GEMS_2012.SYS_EMP_ID_NR)

And I get an incorrect syntax near the word 'AS' error and incorrect syntax near '='

I have read my SQL books and cannot seem to find an explanation on the method to do this, any help would be greatly appreciated.

like image 576
user2119980 Avatar asked Mar 04 '13 14:03

user2119980


1 Answers

You need two do two step:

  1. Use the UNION ALL, like it was mentioned. But if a column is missing you should use NULL for that column.

  2. You should insert the result in a new table.

So it should look like:

SELECT * 
INTO   yournewtablename 
FROM   (SELECT col1, 
               col2, 
               col3 
        FROM   col_tbl_2010_trn_results_new 
        UNION ALL 
        SELECT col1, 
               col2, 
               col3 
        FROM   col_tbl_trn_results_gems_2011 
        UNION ALL 
        SELECT col1, 
               col2, 
               NULL AS Col3 
        FROM   col_tbl_trn_results_gems_2012) n 

Here is a demo to show: SQL FIDDLE

like image 82
András Ottó Avatar answered Oct 05 '22 18:10

András Ottó