简体   繁体   English

SQL Server-将表连接到自身时无效的对象名

[英]SQL Server - Invalid object name while joining table to itself

I've tried to find an answer to my problem but couldn't find similar example. 我试图找到问题的答案,但是找不到类似的例子。

I have results from such a query 我有这样的查询结果

SELECT * FROM (
   SELECT id FROM table
) AS t1

Now I would like to join t1 to another instance of itself because I need to shift it. 现在,我想将t1加入到其自身的另一个实例中,因为我需要对其进行转换。 For example if I wanted to compare a row with the previous one. 例如,如果我想将一行与上一行进行比较。 I tried: 我试过了:

SELECT * FROM (
   SELECT id FROM table
) AS t1
LEFT JOIN t1 AS t2 ON (my conditions)

But I get an error that t1 is invalid object name. 但是我得到一个错误,即t1是无效的对象名称。 When I copy my select statement: 当我复制选择语句时:

SELECT * FROM (
   SELECT id FROM table
) AS t1
LEFT JOIN (
   SELECT id FROM table
) AS t2 ON (my conditions)

The above works, but is it not slower than joining to already returned results? 上面的方法有效,但是它不比加入已经返回的结果慢吗?

Any help would be appreciated 任何帮助,将不胜感激

The first one is in correct: 第一个是正确的:

SELECT * FROM (
   SELECT id FROM table
) AS t1
LEFT JOIN t1 AS t2 ON (my conditions)

Because you can't alias an alias. 因为您不能为别名起别名。 You can do something similar to it using CTE like so: 您可以使用CTE进行类似的操作:

;WITH cte
AS
(
    SELECT * FROM Table   
)
SELECT *
FROM Cte t1
INNER JOIN cte t2 ON --

I think your select should be of the form: 我认为您的选择应采用以下形式:

SELECT * 
FROM [table] t1
LEFT JOIN [table] t2 ON (your conditions)

From a performance perspective, this is identical to your last select and to the CTE solution in Mahmoud's answer (I've reviewed the execution plan for all three in SQL Server). 从性能的角度来看,这与您的上次选择以及Mahmoud的答案中的CTE解决方案相同(我已审查了SQL Server中这三个方案的执行计划)。

It might only be a matter of taste, but I find this form to be more readable/maintainable. 这可能只是一个品味问题,但我发现此表格更具可读性/可维护性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM