문제

I have a table structure where there are CARS going between BUILDINGS that are built on PLOTS:

CARS

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

BUILDINGS

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"

I'm trying to build a query that would show for each CAR, the PLOT coordinates of the origin and destination BUILDINGs, like this:

 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"

This is what I tried but I don't think I'm approaching this right.

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

Could someone please help me understand how to lookup/join for multiple columns (ORIGIN and DEST)?

도움이 되었습니까?

해결책

below is my first thought:

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

다른 팁

Try

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

I created something like this:

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

I know the answers are already here. I add mine here.

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top