2

I would like to combine/merge two select queries by COLUMN and not by rows as shown here with UNION.

Let`s say I have

SELECT attr1, attr2 FROM table1

and

SELECT attr1, attr2 FROM table2

Note, that both tables have the same Attribute Names.

And I want a result with following columns:

attr1_table1, attr2_table1, attr1_table2, attr2_table2

Edit (just for the next as the outer join worked fine):

My first Select Returns something like:

id  attr1  attr2
1   3      5
2   4      6

and my second select

id  attr1 attr2
1   7     9
2   8     10

And my desired result is:

id  attr1 attr2 attr1 attr2
1   3     5     7     9
2   4     6     8     10

Thanks

N.Varela
  • 910
  • 1
  • 11
  • 25

2 Answers2

2

A cross join would be very dangerous because it produces a huge amount of data. E.g. if Table1 and Table2 each have 1000 rows, the result of a cross join would be 1,000,000 rows!

However, I assume you want to line up matching rows. So use the following:

select  COALESCE(t1.id, t2.id) as id,
        t1.attr1, t1.attr2, t2.attr1, t2.attr2
from    Table1 t1
        full outer join Table2 t2 on
            t2.id = t1.id

The full outer join means this also returns rows where no match is found.

Disillusioned
  • 14,635
  • 3
  • 43
  • 77
0

Your question is rather vague. But one possible answer is a cross join:

select t1.attr1 as attr1_1, t1.attr2 as attr2_1,
       t2.attr1 as attr1_2, t2.attr2 as attr2_2
from table1 t1 cross join
     table2 t2;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • What is the different between **table1** and **t1** in from? Aren't both the table name? And therefore only once needed? – N.Varela Feb 06 '18 at 13:16
  • 1
    @N.Varela `t1` and `t2` are aliases defined in the `FROM` clause. You don't need them because you could write `table1.attr1 as attr1_1` etc. But the aliases reduce the code needed to disambiguate the source table. – Disillusioned Feb 06 '18 at 13:19