俞兆丰*_*俞兆丰 1 sql t-sql sql-server
这是我的 SQL
select *
from TableA
where colA1 in (select colA1 from TableB where colB1 = 0)
Run Code Online (Sandbox Code Playgroud)
问题是,colA1中不存在TableB。
所以如果我只是运行这个
select colA1
from TableB
where colB1 = 0
Run Code Online (Sandbox Code Playgroud)
然后 SQL Server Management Studio 将返回错误:
无效的列名“colA1”。
但如果是在where原因中,则可以执行第一个 SQL,就好像原因始终为真一样。
那是因为 SQL Server 首先在 TableB 中查找该列,但没有找到,然后在 TableA 中查找。如果您完全限定您的列名(或使用表别名),您将收到错误,例如
select A.*
from TableA A
where A.colA1 in (
select B.colA1
from TableB B
where B.colB1 = 0
);
Run Code Online (Sandbox Code Playgroud)
本质上,您的查询简化为:
select *
from TableA
where colA1 in (colA1);
Run Code Online (Sandbox Code Playgroud)
这就是为什么你应该总是完全限定你的表名,最好是通过使用简短的、有意义的别名。
| 归档时间: |
|
| 查看次数: |
52 次 |
| 最近记录: |