表一
ID LinkId
1 0
2 1
3 2
表2
ID IntersectionID X Y
1 5 100 200
2 6 300 400
3 7 800 500
表3
ID IntersectionID Sequence_number linkId LinkDirection
1 5 0 0 Positive
1 5 1 1 negative
2 6 0 0 negative
我想要一个查询给我以下
ID LinkId X(start) Y(Start) X(End) Y(End)
1 0 100 200 300 400
对于表1中的每一行,从表3中获取其IntersectionID(使用链接字段),(链接方向 - 正表示起点,负表示终点)。然后转到表2并填充x,y值。
帮助我实现它。
尝试了这个查询。无法得到它。
select r1.id id, r1.linkid base_link_id, r2.X startX,r2.Y startY from table1 r1, table2 r2
where startX = (select X from table2 where id = r1.id and intersectionId =
(select intersectionId from table3 where id = r1.id and linkId= r1.linkid and LinkDirection = positive)) and startY
= (select Y from table2 where id = r1.id and intersectionId =
(select intersectionId from table3 where id = r1.id and linkId= r1.linkid and LinkDirection = negative));
答案 0 :(得分:0)
使用此查询,您应该可以执行此操作。
注意LinkDirection的文字。
SELECT
t1.ID
,t1.LinkId
,t2_start.X as X_Start
,t2_start.Y as Y_Start
,t2_end.X as X_End
,t2_end.Y as Y_End
FROM
table1 t1
LEFT JOIN table3 t3_start
on t1.linkId = t3_start.linkId
and t3_start.LinkDirection = 'Positive'
LEFT JOIN table2 t2_start
on t2_start.IntersectionID = t3_start.IntersectionID
LEFT JOIN table3 t3_end
on t1.linkId = t3_end.linkId
and t3_end.LinkDirection = 'negative'
LEFT JOIN table2 t2_end
on t2_end.IntersectionID = t3_end.IntersectionID
如果table2中没有行,您将在t2_start.X t2_start.Y t2_end.X t2_end.Y
中获得空字段。您可以使用
CASE WHEN t2_start.X is not null THEN t2_start.X ELSE -1 END
答案 1 :(得分:0)
如果您需要澄清,希望以下查询有用。请问
SELECT ID,LinkID,MAX(StartX) AS StartX ,MAX(Starty) AS StartY,
MAX(EndX) AS EndX,MAX(EndY) AS EndY FROM
(
SELECT a.ID,a.LinkID,X as StartX,Y as StartY,null as EndX,null as EndY
FROM
table1 a JOIN table3 b
ON a.Linkid=b.Linkid
JOIN table2 c
ON b.id=c.id WHERE LinkDirection='Positive'
UNION ALL
SELECT a.ID,a.LinkID,null as StartX,null as StartY,X as EndX,Y as EndYY
FROM
table1 a JOIN table3 b
ON a.Linkid=b.Linkid
JOIN table2 c
ON b.id=c.id WHERE LinkDirection='Negative'
) t
GROUP BY ID,LinkID
这将返回
ID LinkID StartX StartY EndX EndY
1 0 100 200 300 400
2 1 NULL NULL 100 200