在 INNER JOIN 查询中使用别名?

Using an ALIAS in an INNER JOIN query?

我认为标题很好地解释了我的问题,我在论坛和其他方面看了很多主题,但我仍然卡住了。我真的不明白该怎么做,也许这里有人能让我明白。 (我希望)

我的查询在这里:

SELECT Name, A, B, C, D, E, F 
FROM Data 
    INNER JOIN User_Access ON Data.Name = User_Access.Name 
WHERE User_Access.Channel = 'TEST'

我知道我必须为 "Name" 使用别名,但我做不到。

目前,我认为我最好的 almost-answer 我的问题是:

SELECT Name AS N, A, B, C, D, E, F 
FROM Data 
    INNER JOIN User_Access ON Data.N = User_Access.Name 
WHERE User_Access.Channel = 'TEST'

但它不起作用,我有一个无效的名称错误。

提前感谢您的帮助!

如果列名在 n 个表之间是通用的,您需要对其进行限定,以便 sql 知道您 mean.This 将使用哪个

SELECT data.Name, A, B, C, D, E, F 
FROM Data 
    INNER JOIN User_Access ON Data.Name = User_Access.Name 
WHERE User_Access.Channel = 'TEST'

如愿

SELECT d.Name, A, B, C, D, E, F 
FROM Data d
    INNER JOIN User_Access ON d.Name = User_Access.Name 
WHERE User_Access.Channel = 'TEST'

来自 Logical Processing Order of the SELECT statement:

The following steps show the logical processing order, or binding order, for a SELECT statement. This order determines when the objects defined in one step are made available to the clauses in subsequent steps. For example, if the query processor can bind to (access) the tables or views defined in the FROM clause, these objects and their columns are made available to all subsequent steps. Conversely, because the SELECT clause is step 8, any column aliases or derived columns defined in that clause cannot be referenced by preceding clauses. However, they can be referenced by subsequent clauses such as the ORDER BY clause. The actual physical execution of the statement is determined by the query processor and the order may vary from this list.

  1. FROM
  2. ON
  3. JOIN
  4. WHERE
  5. GROUP BY
  6. WITH CUBE or WITH ROLLUP
  7. HAVING
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP

注意 SELECT 在位置 8,而 JOINON 分别在位置 3 和 2。因此,您 不能 通过在 ON 中的 SELECT 中定义的别名来引用列;因为 SELECT 尚未处理。实际上,唯一可以通过别名(在同一范围内)引用列的地方是 ORDER BY.

如果你真的想要这样做,你可以使用 as CROSS APPLYVALUES 运算符,但是(老实说)你想输入 N 而不是 ON 中的 Name 更懒惰:

SELECT V.N, D.A, D.B, D.C, D.D, D.E, D.F --I assume there are all from the Data table
FROM Data D
    CROSS APPLY (VALUES(D.[Name])) V(N)
    INNER JOIN User_Access UA ON V.N = UA.Name 
WHERE UA.Channel = 'TEST';
SELECT User_Access.Name, A, B, C, D, E, F 
FROM Data 
    INNER JOIN User_Access ON Data.N = User_Access.Name 
WHERE User_Access.Channel = 'TEST'

我已将名称(关键字)替换为 User_Access.Name(更改附加了实际 table 名称的列名)。

Name是保留字,需要用方括号括起来

SELECT [Name], A, B, C, D, E, F 
FROM Data 
    INNER JOIN User_Access ON Data.N = User_Access.Name 
WHERE User_Access.Channel = 'TEST'