无法创建SQL联接查询
表一 表2无法创建SQL联接查询,sql,join,Sql,Join,表一 表2 ID LinkId 1 0 2 1 3 2 表3 ID IntersectionID X Y 1 5 100 200 2 6 300 400 3 7 800 500 我想要一个单一的查询给我以下信息 ID IntersectionID Sequence_number linkId LinkDirection 1 5
ID LinkId
1 0
2 1
3 2
表3
ID IntersectionID X Y
1 5 100 200
2 6 300 400
3 7 800 500
我想要一个单一的查询给我以下信息
ID IntersectionID Sequence_number linkId LinkDirection
1 5 0 0 Positive
1 5 1 1 negative
2 6 0 0 negative
对于表1中的每一行,从表3(使用链接字段)中获取其IntersectionID,(链接方向-正表示起点,负表示终点)。然后转到表2,填入x,y值
帮我实现它
已尝试此查询。无法得到它
ID LinkId X(start) Y(Start) X(End) Y(End)
1 0 100 200 300 400
通过这个查询,您应该能够完成它 如果是文本,请注意链接方向
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));
如果表2中没有行,您将在t2\u start.X t2\u start.Y t2\u end.X t2\u end.Y中获得空字段。您可以使用将其更改为0或-1
如果t2_start.X不为空,则t2_start.X ELSE-1 END
如果需要澄清,希望下面的查询有用。请问
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
这会回来的
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
什么是shapepointtype,在表1中没有这样的列。@kaleel:忽略它。我已将其从查询中删除。道歉!你在使用哪种数据库管理系统?这就是为什么我喜欢ORM框架或工具。我一点也不喜欢sql命令。你应该看看我的答案:)@Ryx5我在发布我的答案之前做的。请更正以下更改,LinkDirection属于表3而不是表2,左侧联接返回空行,起始值和结束值将显示在单独的行中。@Ryx5它的工作方式。提示:若要删除带有null的记录,请使用Join而不是Left Join。我认为获取null值(并在需要时进行更改)很有趣。很高兴与您共享。@Ryx5:非常感谢。:)很好的一天!
ID LinkID StartX StartY EndX EndY
1 0 100 200 300 400
2 1 NULL NULL 100 200