kamil
kamil

Reputation: 119

SQL: linking two different columns in one

I need to link 2 tables in one big table. My problem is that I need to link 2 different columns (in example: books, toys) in one column (things). Other columns:

Example: table 1:

books cover price
----- ----- ------
book1 soft  19
book2 soft  23
book3 hard  39

table2:

toys  name price
----  ---- -----
astro Buzz 29
mouse Jerr 35

Result:

things name cover price
------ ---- ----- -----
book1  null soft  19
book2  null soft  23
book3  null hard  39
astro  Buzz null  29
mouse  Jerr null  35

Upvotes: 0

Views: 57

Answers (3)

Licantropo
Licantropo

Reputation: 54

You could use the Cross Apply like this using your exmaple

select * from table1 cross apply table2

or you could use the UNION ALL

SELECT books as 'THINGS', NULL as 'NAME', COVER, PRICE
FROM table1
UNION ALL
SELECT toys 'THINGS', NAME, NULL 'COVER', PRICE
FROM table2

Upvotes: 0

Harsh
Harsh

Reputation: 1319

How about a simple UNION:

select books as things, null as name, cover, price
from table1
union
select toys as things, name, null as cover, price from table2

Upvotes: 0

JanR
JanR

Reputation: 6130

You can try using a UNION ALL more info here

Something like this:

SELECT books "things", NULL "name", cover, price
FROM table1
UNION ALL
SELECT toys "things", name , NULL "cover", price
FROM table2

Upvotes: 3

Related Questions