Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union with different number of columns

Tags:

sql

postgresql

I have three columns in the first table, the second table have one column that exists in the first table and 2 I want to add.

Ex:

select  c1 as col1, c2 as col2, c3 as col3
from    Table1
union
select  c1, c4 as col4, c5 as col5
from    Table2

expected Result:

col1,col2,col3,col4,col5
like image 328
Giovane Avatar asked Dec 04 '22 09:12

Giovane


2 Answers

Just add null or any other default value you like as static column

select  c1 as col1, 
        c2 as col2, 
        c3 as col3, 
        null as col4, 
        null as col5
from    Table1
union
select  c1, 
        null, 
        null, 
        c4,
        c5
from    Table2 
like image 98
juergen d Avatar answered Dec 20 '22 22:12

juergen d


You've already asked that question, and got a answer - https://stackoverflow.com/questions/18923218/unioning-tables-with-different-number-of-columns/18923250#18923250. Is there's a possibility that actually you need a join, not union:

select
    t1.c1 as col1,
    t1.c2 as col2,
    t1.c3 as col3,
    t2.c4 as col4,
    t2.c5 as col5
from Table1 as t1
    inner join Table2 as t2 on t2.col1 = t1.col1
like image 38
Roman Pekar Avatar answered Dec 20 '22 20:12

Roman Pekar