Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL Union two tables without relation and return separate columns

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is it possible?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading