Home > database >  SQL Union two tables without relation and return separate columns
SQL Union two tables without relation and return separate columns

Time:05-23

I have to tables 'Table1, Table2' which are not related at all, but I need to do a common query with both because a filter.

I thought about this solution:

select * from(
 select t1.idT1 from Table1 t1 where idT1 = 1
 union all
 select t2.idT2 from Table2 t2 where idT2  = 1) as results

but it returns me a single column named idT1 and what I need is two separated columns: 'idT1', 'idT2' because I need to know if id is from table 1 or table 2 to look for their details later.

Is it possible?

CodePudding user response:

select * from(
 select t1.idT1, null as IdT2 from Table1 t1 where idT1 = 1
 union all
 select null as idT2, t2.idT2 from Table2 t2 where idT2  = 1) as results

or as @jarlh suggested

select * from(
 select 't1' as T1OrT2, t1.idT1 from Table1 t1 where idT1 = 1
 union all
 select 't2' as T1OrT2, t2.idT2 from Table2 t2 where idT2  = 1) as results

I am assuming that where IdT1=1 in your question is just an example, because if it is really that then the result will be all 1s, as @Nathan_Sav pointed out.

  • Related