SQL在三个连接表上查找值

时间:2014-03-20 22:11:28

标签: sql sql-server join lookup-tables

我有一个表格结构,CARS之间的BUILDINGS之间有PLOTS

CARS

CAR_ID  |  ORIGIN  |   DESTINATION
----------------------------------
   1    |    A     |       C
   2    |    B     |       A
   3    |    A     |       B

建筑物

BUILD_ID  |   PLOT
------------------
   A      |    2
   B      |    1
   C      |    3

PLOTS

PLOT_ID  |  COORD
------------------------
  1      |  "39.9,-75.5"
  2      |  "38.3,-74.7"
  3      |  "37.8,-76.1"

我正在尝试构建一个查询,该查询将显示每个CARPLOT坐标原点和目标BUILDING,如下所示:

 CAR_ID   |   ORIGIN_COORD   |   DEST_COORD
-------------------------------------------
  1       |   "38.3,-74.7"   | "37.8,-76.1"
  2       |   "39.9,-75.5"   | "38.3,-74.7"
  3       |   "39.9,-75.5"   | "39.9,-75.5"

这就是我的尝试,但我不认为我正在接近这一点。

SELECT * FROM
   (SELECT BUILD_ID, PLOT, COORD FROM BUILDINGS
    INNER JOIN PLOTS ON PLOT = PLOT_ID) X
RIGHT JOIN CARS C
ON C.ORIGIN = X.BUILD_ID

有人可以帮助我了解如何查找/加入多个列(ORIGINDEST)吗?

4 个答案:

答案 0 :(得分:3)

下面是我的第一个想法:

select c.car_id,p1.coord as origin_coord, p2.coord as dest_coord
from cars as c
join buildings as b1 on b1.build_id=c.origin
join buildings as b2 on b2.build_id=c.destination
join plots as p1 on p1.plot_id=b1.plot
join plots as p2 on p2.plot_id=b2.plot

答案 1 :(得分:1)

尝试

SELECT C.car_id, po.coord as origin_coord, pd.cooord as dest_coord FROM Cars as C JOIN Buildings as o on c.origin = o.build_id JOIN Buildings as d on c.destination = d.build_id JOIN Plots as po on po.plot_id = o.plot JOIN Plots as pd on pd.plot_id = d.plot ORDER BY C.car_id

答案 2 :(得分:1)

我创造了这样的东西:

SELECT A.CAR_ID, B2.COORD AS ORIGIN, C2.COORD AS DESTINATION
FROM CARS AS A
LEFT JOIN BUILDINGS AS B
ON A.ORIGIN = B.BUILD_ID
LEFT JOIN PLOTS AS B2
ON B.PLOT = B2.PLOT_ID
LEFT JOIN BUILDINGS AS C
ON A.DESTINATION = C.BUILD_ID
LEFT JOIN PLOTS AS C2
ON C.PLOT = C2.PLOT_ID

答案 3 :(得分:0)

我知道答案已经在这里了。我在这里加我的。

select c.car_id, 
p1.coord as OriginCoord,
p2.coord as DestinationCoord
from cars as c
    left outer join buildings as b1
        on c.origin = b1.build_id
    left outer join buildings as b2 
        on c.destination = b2.build_id
    left outer join plots as p1
        on b1.plot = p1.plot_id
    left outer join plots as p2
        on b2.plot = p2.plot_id
order by c.car_id