首页 > 解决方案 > 编写嵌套 SQL 查询时不使用别名

问题描述

我最近问了一个关于别名的问题:Discerning between alias, temp table, etc [SQL Server]

我的印象是表和结果查询必须使用别名命名。

select customers.name as 'Customers'
from customers
where customers.id not in
(
    select customerid from orders 
) 

事实上,当您使用别名时,会出现运行时错误。是什么赋予了?

标签: sql-server

解决方案


当使用“表”时——即任何可以使用 JOIN 的东西——需要某种名称。例如,如果您的查询写成:

select customers.name as 'Customers'
from customers
LEFT JOIN (
    select customerid from orders
    ) ___
WHERE ___ is null

然后您需要命名派生表,并填写空白,因为 SQL 语法需要在 JOIN 语句中命名。

但是,在您的示例代码中:

select customers.name as 'Customers'
from customers
where customers.id not in
(
    select customerid from orders 
)

语法不需要名称,因此嵌套查询不需要命名。


推荐阅读