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

前端 未结 5 929
我寻月下人不归
我寻月下人不归 2020-12-07 12:07

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, s

5条回答
  •  离开以前
    2020-12-07 13:00

    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.

提交回复
热议问题