简体   繁体   English

SQL Server无法解析子查询

[英]Sql server not parsing Sub-query

I have the below query in SQL server 2012 which is running fine when the whole query is run, but the inner query is not running individually because AdviceRecordID doesn't belong to tblB. 我在SQL Server 2012中有以下查询,当运行整个查询时,该查询运行良好,但是内部查询没有单独运行,因为AdviceRecordID不属于tblB。

SELECT DISTINCT SubLOBID 
FROM tblA 
WHERE AdviceRecordID 
IN (SELECT AdviceRecordID
    FROM tblB
)

The first case, where the whole query is run, is not considering the WHERE condition at all and returing all the results without any error which is strange for me. 第一种情况是整个查询都在运行,根本没有考虑WHERE条件,而是重试了所有结果而没有任何错误,这对我来说很奇怪。

This works as expected and required by the SQL standard. 这按SQL标准的预期和要求运行。 If a subquery references a column that is not available in the tables of the subquery, but is a valid column in the outer query, the value from the outer query's column is used. 如果子查询引用的子列在子查询的表中不可用,但在外部查询中是有效列,则使用外部查询的列中的值。

So the query: 所以查询:

SELECT DISTINCT SubLOBID 
FROM tblA 
WHERE AdviceRecordID IN (SELECT AdviceRecordID
                         FROM tblB);

Is in fact a co -related subquery and is parsed and executed as: 实际上是一个与co相关的子查询,并且被解析并执行为:

SELECT DISTINCT SubLOBID 
FROM tblA 
WHERE AdviceRecordID IN (SELECT tblA.AdviceRecordID
                         FROM tblB);

So for each row in tblA the subquery returns the value of tblA.AdviceRecordID once for each row in tblB and compares that to the rules of the IN operator. 所以对于每一行tblA子查询返回的值tblA.AdviceRecordID在每一行一次tblB ,并比较了该规则的IN操作符。

That's why the query as a whole is valid, and behaves like no where clause was used as the above is equivalent to: 这就是查询整体上有效的原因,并且其行为就像没有使用where子句一样,因为上述等效于:

SELECT DISTINCT SubLOBID 
FROM tblA 
WHERE AdviceRecordID IS NOT NULL;

And if there are no NULL values in the column AdviceRecordID then the WHERE clause is not filtering out anything. 并且,如果AdviceRecordID列中没有NULL值,则WHERE子句不会过滤掉任何内容。

Better to use EXISTS instead of IN clause. 最好使用EXISTS代替IN子句。

Check the difference: 检查差异:

Difference1 Difference1

Difference2 Difference2

SELECT DISTINCT A.SubLOBID 
FROM tblA A
WHERE EXISTS 
(
    SELECT B.AdviceRecordID
    FROM tblB B
    WHERE B.AdviceRecordID=A.AdviceRecordID
)

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

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