别名

改进 SQL Server 中的查询性能

Dean Smith

Founder, Atamai Analytics

什么是别名?

  • 在查询中用于标识:
    • 子查询
  • 临时,仅在运行时生效
  • 使查询更易读
  • 有时是必需的
改进 SQL Server 中的查询性能

为什么用别名?

  • 避免重复使用冗长的表/列名
  • 易于识别连接的表及其列
  • 标识新列
  • 标识子查询
  • 当连接表含同名列时避免歧义
  • 重命名列
改进 SQL Server 中的查询性能

连接表——列名不明确

SELECT CountryName, 
       Code2, 
       Capital, 
       Pop2017
FROM Nations
INNER JOIN Cities
  ON Capital = CityName;
-----------------------------------------------
-- 错误,Pop2017 列同时存在于
Nations 和 Cities 表中

Ambiguous column name 'Pop2017'.
改进 SQL Server 中的查询性能

连接表——表名设别名

-- 表别名;Nations 为 n,Cities 为 c
SELECT n.CountryName, 
       n.Code2, 
       n.Capital, 
       c.Pop2017 -- 城市人口
FROM Nations AS n
INNER JOIN Cities AS c
  ON n.Capital = c.CityName;
CountryName Code2 Capital Pop2017
United Kingdom GB London 346774
Canada CA Ottawa 874433
France FR Paris 10437
Reunion RE Saint-Denis 1067
... ... ... ...
改进 SQL Server 中的查询性能

重命名列

-- 列别名;
SELECT n.CountryName AS Country, 
       n.Code2 AS CountryCode, 
       n.Capital, 
       c.Pop2017 AS Population
FROM Nations AS n
INNER JOIN Cities AS c
  ON n.Capital = c.CityName;
Country CountryCode Capital Population
United Kingdom GB London 346774
Canada CA Ottawa 874433
France FR Paris 10437
Reunion RE Saint-Denis 1067
... ... ... ...
改进 SQL Server 中的查询性能

新列

-- 新列别名为 MaxMagnitude
SELECT Country, 
       NearestPop AS City,
       MAX(Magnitude) AS MaxMagnitude
FROM Earthquakes 
GROUP BY Country, NearestPop;
Country City MaxMagnitude
PE Acar 7.1
US Aguadilla 7.7
MX Aguililla 7.2
PW Airai 7.8
PG Aitape 7.6
... ... ...
改进 SQL Server 中的查询性能

子查询

SELECT n.CountryName AS Country, 
       n.Capital, 
       e.MaxMagnitude
FROM Nations n
INNER JOIN
        (SELECT Country, NearestPop AS City
                ,MAX(Magnitude) AS MaxMagnitude
        FROM Earthquakes 
        GROUP BY Country, NearestPop) e 
              -- 子查询别名为 e
    ON n.Code2 = e.Country AND n.Capital = e.City;
Country Capital MaxMagnitude
Fiji Suva 7.9
Guam Hagatna 7.8
Peru Lima 7.6
Turkmenistan Ashgabat 7.3
... ... ...
改进 SQL Server 中的查询性能

Passons à la pratique !

改进 SQL Server 中的查询性能

Preparing Video For Download...