我有一个相当简单的SQL语句来从几个表中获取一些结果。其中一列是从内联SQL语句生成的。虽然我似乎能够通过此列进行排序,但尝试使用它进行过滤表示该列无效。这是我的代码和错误:
SELECT
e.Title as Title,
-- Get earliest start time and latest end time
(SELECT TOP 1 l.StartTime FROM Locations l WHERE l.EventID = e.EventID ORDER BY l.StartTime ASC) as EarliestStartTime,
(SELECT TOP 1 l.EndTime FROM Locations l WHERE l.EventID = e.EventID ORDER BY l.EndTime DESC) as LatestEndTime
FROM
Events e
WHERE
e.UserID = @UserID
AND LatestEndTime < DATEADD(DAY, GETDATE(), 1)
ORDER BY
EarliestStartTime ASC
错误:
Invalid column name 'LatestEndTime'.
如果删除AND LatestEndTime < DATEADD(DAY, GETDATE(), 1)
,则该语句可以正常运行。
答案 0 :(得分:6)
您无法在where
子句中通过别名引用列。写出来,重复列定义:
WHERE e.UserID = @UserID
AND (SELECT TOP 1 l.EndTime FROM Locations l
WHERE l.EventID = e.EventID ORDER BY l.EndTime DESC) <
DATEADD(DAY, GETDATE(), 1)
或使用子查询命名列:
select *
from (
select e.Title as Title,
-- Get earliest start time and latest end time
(SELECT TOP 1 l.StartTime FROM Locations l
WHERE l.EventID = e.EventID ORDER BY l.StartTime ASC)
as EarliestStartTime,
(SELECT TOP 1 l.EndTime FROM Locations l
WHERE l.EventID = e.EventID ORDER BY l.EndTime DESC)
as LatestEndTime
from Events e
) as SubQuery
WHERE UserID = @UserID
and LatestEndTime < DATEADD(DAY, GETDATE(), 1)
答案 1 :(得分:0)
可以尝试使用e.LatestEndTime
看起来您的查询无法确定列LatestEndTime。由于您在查询中使用了Locations l AND Events e,因此它不存在或MySQL只是检查false数据库。