正确加入SQL中的表

时间:2014-06-30 14:29:19

标签: sql sql-server-2008

我有两个表在SQLServer2008中命名StationTabs和Links。

StationTabs
------------
StationId(int)
Longitude(float)
Latitude(float)


Links
----
id(int)
StationStart(int)
StationEnd(int)

StationStart和StationEnd是StationId的外键。我应该使用相同的查询获取StationStart和StationEnd的经度和纬度值。我尝试过这样的事情;

Select Longitude,Latitude
From StationTabs, (Select * From Links ) As ST1, (Select * From Links) As ST2
Where ST1.StationStart=StationTabs.StationId  AND ST2.StationEnd=StationTabs.StationId;

此语句仅返回StationEnd的经度和纬度值。有人可以帮忙吗?

例如;

StationId = 1, Longitude = 35,18, Latitude = 37,01
StationId = 2, Longitude = 36,43, Latitude = 38,88

在链接表中;

id = 3, StationStart = 2 , StationStart = 1

结果,我必须得到

的值
lonStart=36,43 and latStart = 38,88
lonEnd=35,18 and latEnd=37,01

4 个答案:

答案 0 :(得分:4)

这应该有效:

SELECT Longitude, 
       Latitude 
FROM   StationTabs st
INNER JOIN Links lStart
    ON st.StationId = lStart.StationStart
INNER JOIN Links lEnd
    ON st.StationId = lEnd.StationEnd

如果其中一个(或两者)都可以为null,但您想要包含此记录,则应使用LEFT OUTER JOIN代替。

答案 1 :(得分:1)

您的子选择完全没有意义,应该写成常规的JOIN操作:

SELECT Longitude, Latitude, ST1.id, ST2.id
FROM StationTabs
LEFT JOIN Links AS ST1 on StationTabs.StationID = ST1.StationStart
LEFT JOIN Links AS ST2 on StationTabs.StationID = ST2.StationEnd

答案 2 :(得分:0)

如果您想要获取每个Links条目的开始和结束纬度/经度值,那么您对错误表格的引用加倍:

SELECT
    ST1.Longitude as StartLong,
    ST1.Latitude as StartLat,
    ST2.Longitude as EndLong,
    ST2.Latitude as EndLat,
    l.ID as LinkID
FROM
   Links l
      inner join
   StationTabs ST1
      on
          l.StationStart = ST1.StationId
      inner join
   StationTabs ST2
      on
          l.StationEnd = ST2.StationId

答案 3 :(得分:0)

Select Long,Lat From StationTabs where (StationId  IN (Select StationStart From Links) OR StationId IN (select StationEnd from Links))