SELECT BusLine.LineCode AS RouteID,
BusStation.Station AS StartStation, BusStation_1.Station AS EndStation,
BusStation_1.StationIndex - BusStation.StationIndex AS StopCount
FROM BusLine AS BusLine_1
INNER JOIN Area AS Area_1
ON BusLine_1.AreaID = Area_1.ID
INNER JOIN BusInfo AS BusInfo_1
ON BusLine_1.ID = BusInfo_1.BusLineID
INNER JOIN BusStation AS BusStation_1
ON BusInfo_1.ID = BusStation_1.BusInfoID
INNER JOIN
Area
INNER JOIN BusLine
ON Area.ID = BusLine.AreaID
INNER JOIN BusInfo
ON BusLine.ID = BusInfo.BusLineID
INNER JOIN BusStation
ON BusInfo.ID = BusStation.BusInfoID
ON BusStation_1.StationIndex > BusStation.StationIndex AND BusInfo_1.ID = BusInfo.ID
WHERE (Area.City = 'NewYork')
我已经阅读了上面的sql十分钟,但由于这一行我无法理解:
INNER JOIN
Area
INNER JOIN BusLine
我想知道是否有人可以解释它并重新考虑它以使其易于理解?
更新架构:
区域:
ID
Name
乘车路线:
ID
AreaID --> ID in Area
LineCode
BusInfo:
ID
BusLineID --> ID in BusLine
站点巴士:
BusInfoID --> ID in BusInfo
BTW,我正在使用Access,似乎我必须使用( )
来包装innjer join
。
答案 0 :(得分:2)
原作者已经足够周到地以一种指示联接在逻辑上相关的方式缩进SQL。
可以改写为:
FROM BusLine AS BusLine_1
INNER JOIN Area AS Area_1
ON BusLine_1.AreaID = Area_1.ID
INNER JOIN BusInfo AS BusInfo_1
ON BusLine_1.ID = BusInfo_1.BusLineID
INNER JOIN BusStation AS BusStation_1
ON BusInfo_1.ID = BusStation_1.BusInfoID
INNER JOIN BusStation
ON BusStation_1.StationIndex > BusStation.StationIndex
INNER JOIN BusInfo
ON BusInfo.ID = BusStation.BusInfoID AND BusInfo_1.ID = BusInfo.ID
INNER JOIN BusLine
ON BusLine.ID = BusInfo.BusLineID
INNER JOIN Area
ON Area.ID = BusLine.AreaID
WHERE (Area.City = 'NewYork')
编辑:我应该补充一点,嵌套的内连接语法只是一种表示优先级的方法,即这组连接应该(逻辑上)在其他连接之前执行。一些SQL引擎支持使用括号来实现此目的。在所有连接都是内连接的情况下,嵌套和非嵌套表单之间没有逻辑差异(即您提供的SQL和我上面提供的备用SQL)。
答案 1 :(得分:1)
令你困惑的事情并不是你所强调的部分。 INNER JOIN Area
首先加入上述部分,因为以下部分INNER JOIN BusLine ON Area.ID = BusLine.AreaID
是带有子句的常规标准联接。
如果(如果这是一个很大的话)我已经正确地阅读了这个问题(公交线路离开纽约时他们有多少站点),这就是我的意思。试着重构它
SELECT BusLine.LineCode AS RouteID,
BusStation.Station AS StartStation, BusStation_1.Station AS EndStation,
BusStation_1.StationIndex - BusStation.StationIndex AS StopCount
FROM BusLine AS BusLine_1
INNER JOIN Area AS Area_1
ON BusLine_1.AreaID = Area_1.ID
INNER JOIN BusInfo AS BusInfo_1
ON BusLine_1.ID = BusInfo_1.BusLineID
INNER JOIN BusStation AS BusStation_1
ON BusInfo_1.ID = BusStation_1.BusInfoID
INNER JOIN Area
ON BusStation_1.StationIndex > BusStation.StationIndex AND BusInfo_1.ID = BusInfo.ID AND Area.City = 'NewYork'
INNER JOIN BusLine
ON Area.ID = BusLine.AreaID
INNER JOIN BusInfo
ON BusLine.ID = BusInfo.BusLineID
INNER JOIN BusStation
ON BusInfo.ID = BusStation.BusInfoID
请告诉我结果集是否相同!