Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I merge the columns from two tables into one output?

Tags:

sql

postgresql

People also ask

How do I combine two columns from different tables in SQL?

Select the same number of columns for each query. Corresponding columns must be the same general data type. Corresponding columns must all either allow null values or not allow null values. If you want to order the columns, specify a column number because the names of the columns you are merging are probably different.

What would you use to combine columns from two different tables?

Simply put, JOINs combine data by appending the columns from one table alongside the columns from another table. In contrast, UNIONs combine data by appending the rows alongside the rows from another table. Note the following when using UNION in SQL: All SELECT statements should list the same number of columns.


Specifying the columns on your query should do the trick:

select a.col1, b.col2, a.col3, b.col4, a.category_id 
from items_a a, items_b b 
where a.category_id = b.category_id

should do the trick with regards to picking the columns you want.

To get around the fact that some data is only in items_a and some data is only in items_b, you would be able to do:

select 
  coalesce(a.col1, b.col1) as col1, 
  coalesce(a.col2, b.col2) as col2,
  coalesce(a.col3, b.col3) as col3,
  a.category_id
from items_a a, items_b b
where a.category_id = b.category_id

The coalesce function will return the first non-null value, so for each row if col1 is non null, it'll use that, otherwise it'll get the value from col2, etc.


I guess that what you want to do is an UNION of both tables.

If both tables have the same columns then you can just do

SELECT category_id, col1, col2, col3
  FROM items_a
UNION 
SELECT category_id, col1, col2, col3 
  FROM items_b

Else, you might have to do something like

SELECT category_id, col1, col2, col3
  FROM items_a 
UNION 
SELECT category_id, col_1 as col1, col_2 as col2, col_3 as col3
  FROM items_b

The top answer assumes that neither result is null. In my requirement i had two tables that needed to be made 1 with no join constraint. I was just combining them.

If you want to get results regardless of 1 is null or not.

select a.col1, b.col2, a.col3, b.col4, a.category_id 
from items_a a
  full outer join items_b b 
  on 1=1
 

Should do the trick. When i was doing this practically i had to go even further and use table expressions for my two "sets" I wanted to join together and then full outer join the two sets.