Search code examples
mysqlmysql-error-1064

MySQL Joins of tables with different columns


I want to create a table that needs to be a combination of selected columns from three or more tables. I don't have any sample data, just added the columns for explanation.

Table 1

A|B1|C1|D1|E1|F1|G1|H1|I1|J1

Table 2

A|B2|C2|D2|E2|F2|G2

Table 3

A|B3|C3|D3|E3|F3|G3

Resultant New table must have

A|B1|E1|F1|G1|J1|C2|D2|G2|B3|D3|F3

I'm not sure if I need to use a FULL JOIN or use UNIONS. Each of these tables contain more than 400,000 rows. Any help here on what query needs to be included would be really helpful.


Solution

  • You can try the below query:

    select t1.A,t1.B1,t3.E1,t1.F1,t1.G1,t1.J1,t2.C2,t2.D2,t2.G2,t3.B3,t3.D3,t3.F3 
    from table1 t1  join table2 t2 on t1.A = t2.A
    join table3 t3 join table2 t2 on t3.A = t2.A
    

    As Palec commented correctly in the other answer, so adding a bit of explanation to the answer.

    You need to use the JOINS for this problem instead of UNION. The reason why I am saying to use JOINS over UNION is UNION combines the data/result of two or more queries into a single result set which includes all the rows which exist in the queries in your UNION. But when you are using JOINs, you can retrieve data from two or more tables based on logical relationships between the tables.

    Also to add that you should add an alias name to your table so that it becomes easy to retrieve the column in the select query and also while linking the table.