加入两个连接的结果

时间:2018-03-13 16:45:27

标签: sql join

我正在寻找创建将执行以下操作的查询的最佳方法(注意:这只是一个示例,我知道这个示例可以写得更好,我的真正目标是一个更复杂的例子,但遵循一个类似的结构)

items
       item_id   |   name      | cost

       1         |   Water     | 1.00
       2         |   Chips     | 1.50

trans_local

       local_id           |   item_id   |  date

       1                  |   1         | '2018-03-12'
       2                  |   1         | '2018-03-13'
       3                  |   2         | '2018-03-13'         

trans_international

       international_id   |   item_id   |  currency | date

       1                  |   1         |  'GBP'    | '2018-03-11'
       2                  |   2         |  'EUR'    | '2018-03-12'
       3                  |   2         |  'GBP'    | '2018-03-12'

我正在创建一个select语句,该表列出了其中的所有事务。

 local_id   | international_id |  item_id | item_name | item_cost | currency | date

 1          | null             |  1       | Water     | 1.00      | null     | '2018-03-12'
 2          | null             |  1       | Water     | 1.00      | null     | '2018-03-13'
 3          | null             |  2       | Chips     | 1.50      | null     | '2018-03-13'
 null       | 1                |  1       | Water     | 1.00      | 'GBP'    | '2018-03-11'
 null       | 2                |  2       | Chips     | 1.50      | 'EUR'    | '2018-03-12'
 null       | 3                |  2       | Chips     | 1.50      | 'GBP'    | '2018-03-12'

items应加入trans_localtrans_international。我知道我可以使用LEFT OUTER JOIN执行此操作,但我不确定如何将所有事务的结果放在一起。我相信它会是一个FULL JOIN,但把所有东西放在一起让我感到困惑。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:3)

我认为实现结果的唯一方法是使用UNION查询,如下所示:

(
  SELECT
    NULL as international_id,
    trans_local.local_id,
    items.name as item_name,
    items.cost as item_cost,
    NULL as currency,
    trans_local.date as date
  FROM items
  LEFT JOIN trans_local ON items.item_id = trans_local.item_id
)    
UNION
(
  SELECT
    trans_international.international_id as international_id,
    NULL as local_id,
    items.name as item_name,
    items.cost as item_cost,
    trans_international.currency as currency,
    trans_international.date as date
  FROM items
  LEFT JOIN trans_international ON items.item_id = trans_international.item_id
)

答案 1 :(得分:1)

select local_id , international_id, A.item_id, item_name, item_cost,
currency, B.DATE
from items A
left outer join
trans_local B
on (A.item_id = B.item_id)
left outer join
trans_international C
on (A.item_id = C.item_id)

根据您的要求,您的item_id列包含所有值。所以找到表中你想要所有值的列,并将其作为左外连接。

答案 2 :(得分:1)

我想你想要一个union all

select i.*, t.*
from ((select local_id, NULL as internationalid, item_id, null as currency, date
       from trans_local
      ) union all
      (select NULL as local_id, internationalid, item_id, currency, date
       from trans_international
      )
     ) t join
     item i
     on t.item_id = i.item_id;