从两个外键字段,SQL,双连接获取规范化值?

时间:2011-08-05 18:21:41

标签: sql

一个例子是解释我想要做的最简单的方法:

下式给出:

~move~
id | from | to
--------------
 1 |  1   | 2
 2 |  1   | 2
 3 |  2   | 3
 4 |  3   | 1

 ~locations~ 
 id | name
 ---------
  1 | home
  2 | work
  3 | out

我怎样才能得到:

id | from | to
----------------
 1 | home | work
 2 | home | work
 3 | work | out
 4 | out  | home

的人类可读名称 fromto列。

1 个答案:

答案 0 :(得分:4)

Select
  Move.ID,
  [From] = FromLocation.Name,
  [To] = ToLocation.Name
From
  Move
  Inner Join Location As FromLocation On Move.[From] = FromLocation.ID
  Inner Join Location As ToLocation On Move.[To] = ToLocation.ID