SQL子查询,无效的列名称

时间:2014-06-24 09:28:40

标签: sql sql-server

TSQL表示:列名无效' VehicleId'

SELECT 
(SELECT dbo.Vehicles.Id FROM dbo.Vehicles JOIN dbo.Movements 
ON dbo.Vehicles.Id=dbo.Movements.VehicleId 
WHERE dbo.Movements.Id=dbo.Alarms.MovementId) As VehicleId
FROM [dbo].[Alarms] 
WHERE 
VehicleId =1

有什么问题?

3 个答案:

答案 0 :(得分:1)

Alarms没有名为VehicleId

的列

where子句不使用别名

SELECT 
(SELECT dbo.Vehicles.Id FROM dbo.Vehicles JOIN dbo.Movements 
ON dbo.Vehicles.Id=dbo.Movements.VehicleId 
WHERE dbo.Movements.Id=dbo.Alarms.MovementId) As VehicleId
FROM [dbo].[Alarms] 
WHERE 
VehicleId = 1 -- this is wrong

而不是使用相关子查询尝试多个连接

SELECT dbo.Vehicles.Id 
FROM dbo.Vehicles 
JOIN dbo.Movements 
ON dbo.Vehicles.Id = dbo.Movements.VehicleId 
JOIN dbo.Alarms
ON dbo.Alarms.MovementId = dbo.Movement.Id
WHERE dbo.Movements.VehicleId = 1

答案 1 :(得分:0)

试试这个

SELECT Alarms.*
from 
(SELECT dbo.Vehicles.Id FROM dbo.Vehicles JOIN dbo.Movements 
ON dbo.Vehicles.Id=dbo.Movements.VehicleId 
WHERE dbo.Movements.Id=dbo.Alarms.MovementId) As VehicleId
join  [dbo].[Alarms] 
on VehicleId.ID = Alarms.vehicleID
WHERE 
VehicleId =1

答案 2 :(得分:0)

我想,你正在寻找这样的东西:

SELECT Alarms.*
FROM dbo.Vehicles JOIN 
        dbo.Movements ON dbo.Vehicles.Id=dbo.Movements.VehicleId JOIN
        dbo.Alarms ON dbo.Movements.Id=dbo.Alarms.MovementId
WHERE VehicleId =1