tags:

views:

128

answers:

2

I have two tables with similar information. Let's call them items_a and items_b. They should be one, but they are coming from different sources, so they aren't. When I full-join the two table, some rows end up with data from either one or both tables. One of the columns in both tables is category_id. I would like to cross the combined table with the categories table using category_id. However, I have two category_id columns now (one from items_a and one from items_b). Is there a way to merge the two columns into one?

I hope this isn't too confusing of a question.

+2  A: 

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.

beny23
coalesce is great!
bigmac
can i also use it in where such as:... where c.col1 = coalesce(a.col1, b.col1)?
bigmac
@bigmac: shouldn't be a problem
beny23
+2  A: 

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
voyager
Your first example isn't a valid `UNION` statement - it should literally be a combination of two SELECT statements. The second example doesn't require the brackets and is otherwise syntactically correct.
OMG Ponies