简体   繁体   English

SQL Server Management Studio中的查询优化

[英]Query optimisation in SQL Server Management Studio

In the query given below, in the where condition the table 'a' is not accessible. 在下面给出的查询中,在where条件下,无法访问表'a'。 How can I make it accessible without affecting the logic of the code? 如何在不影响代码逻辑的情况下使其可访问?

Thanks in advance. 提前致谢。

select * 
from Training_Data.dbo.test a
cross apply (select * from Training_data.dbo.test_table) b
where exists (select 1 from a)

To make the table accessible use real table name instead of alias. 要使表可访问,请使用真实表名而不是别名。

select * 
from Training_Data.dbo.test a
 cross apply (select * from Training_data.dbo.test_table) b
where exists (select 1 from Training_Data.dbo.test)

By the way I suppose that it would be more appropriate to check existence of the data in the table before the select in IF clause and to use cross join instead of cross apply 顺便说一句,我认为在IF子句中的select之前检查表中数据的存在并使用交叉连接而不是交叉应用会更合适。

if exists (select 1 from #T1)
 select *
 from #T1 a
  cross join #T1 b

You can access your referenced tables columns in any EXIST inside your WHERE , you just need a correct syntax. 您可以在WHERE内的任何EXIST访问引用的表列,只需要正确的语法即可。

Example: SELECT if there's a record with same value in another table (reference to a column from table test : 例如: SELECT ,如果有另一个表与相同值的记录(参考从表中的列test

select 
    * 
from 
    Training_Data.dbo.test a
    cross apply (select * from Training_data.dbo.test_table) b
where 
    exists (
        select 
            1 
        from 
            Training_data.dbo.another_test_table c 
        where 
            a.someColumn = c.anotherColumn)

Example: SELECT if there are records on a table (without referencing any column): 例如: SELECT ,如果有记录在表上(不参考任何列):

select 
    * 
from 
    Training_Data.dbo.test a
    cross apply (select * from Training_data.dbo.test_table) b
where 
    exists (
        select 
            1 
        from 
            Training_Data.dbo.test c)

For this last example, if you want to select rows from a table only if they exist in the same table, then your SELECT will already handle that, since it will fetch the rows that are in that table. 对于最后的例子,如果你想从一个表,只有当他们在同一个表中存在选择行,那么你的SELECT都已经搞定,因为它会取那些在表中的行。

A programmer can use an alias to temporarily assign another name to a table or column for the duration of a SELECT query. 程序员可以使用别名在SELECT查询期间将临时名称临时分配给表或列。 Assigning an alias does not actually rename the column or table. 分配别名实际上不会重命名列或表。 This is often useful when either tables or their columns have very long or complex names. 当表或其列的名称很长或很复杂时,这通常很有用。 Hope you got your answer. 希望你能得到答案。 You can put condition using column name if you don't want to change anything, but you can't use alias as table. 如果您不想更改任何内容,则可以使用列名作为条件,但不能将别名用作表。

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

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