通过关系表获取两个表之间的现有和非现有组合

时间:2012-08-07 17:35:26

标签: sql sql-server

我需要帮助。

我有3张桌子(FROM,TOys和DISTANCEs):

FROMs(Id, Name)
1 - London
2 - Beijing
3 - Athens

TOs(Id, Name)
1 - New York
2 - Madrid
3 - Paris

DISTANCEs(Id,FROMid,TOid,km,obs)
1 - 2 - 3 - 400 - distance between Beij. and Paris

我需要一个返回此的查询:

1    - 2 - 3 - 400 - distance between Beij. and Paris
NULL - 1 - 1 - NULL - NULL
所有不存在的组合

等等。

感谢。

1 个答案:

答案 0 :(得分:3)

这样的事情应该做:

以下是SQLFiddle

的链接
select a.id, b.fromId, b.toId, a.km, a.obs from distances a
right join(
select a.id as fromId, 
       a.name as fromName,
       b.id as toId,
       b.name as toName
from froms a
join tos b
on 1=1) b
on a.fromId = b.fromId
   and a.toId = b.toId