无法查询别名表

时间:2015-07-08 14:17:26

标签: sql sql-server-2005

我做了类似的事情:

SELECT T1.NAME, T2.DATE
    FROM T1
INNER JOIN
(
    SELECT * FROM OTHERTABLE
) AS T2 ON T2.USERID = T1.USERID

哪个有效,但如果我查询别名表,我会收到错误,说T2是无效的对象名。

示例:

SELECT 
T1.NAME, 
T2.DATE,
CASE
    WHEN EXISTS (SELECT TOP 1 1 FROM T2 WHERE T2.THISFIELD = T1.THISFIELD) THEN 'HELLO'
    ELSE 'BYE'
END AS COMMENT -- THIS ALSO FAILS
    FROM T1
INNER JOIN
(
    SELECT * FROM OTHERTABLE
) AS T2 ON T2.USERID = T1.USERID
WHERE (SELECT COUNT(*) FROM T2) > 0

我认为这就是我所做的,"创造" T2。有什么方法可以像这样使用T2吗?

我的目标是从OTHERTABLE中删除所有相关数据,因为我在SELECT子句中有很多CASE,具体取决于数据是否存在于T2中。我不想为每个字段做EXISTS,因为每次都会在一个巨大的表中启动一个新的查询。

1 个答案:

答案 0 :(得分:1)

您的查询使用的SELECT * FROM OTHERTABLE子查询没有意义。您可以像修改一样修改它;

SELECT 
T1.NAME, 
T2.DATE,
...

FROM T1
    JOIN OTHERTABLE T2 ON T2.USERID = T1.USERID
WHERE (SELECT COUNT(*) FROM OTHERTABLE ) > 0

您不能在同一查询中多次使用子查询。而是为此目的使用Common Table Expression (CTE)。 T2是以下示例中的CTE。

;WITH T2 AS
(
   SELECT UserId, col1, col2, [Date]
   FROM OtherTable
)
SELECT T1.NAME, T2.DATE
FROM T1
    JOIN T2 ON T2.USERID = T1.USERID
WHERE (SELECT COUNT(*) FROM T2) > 0