简体   繁体   中英

Access: When can a field alias be used in the same select statement?

Many references say that a field alias cannot be used in another field in the same SELECT statement. For example:

However, these statements are false, at least in Access. This can be seen by creating the table [A table] with a field [Table field] and then running the following query:

SELECT 
    [Table field] AS [Query field 1], 
    [Query field 1] & " is a field value." AS [Query field 2] 
FROM [A table];

That works. The alias definition doesn't even have to come before it is referenced:

SELECT 
    [Query field 1] & " is a field value." AS [Query field 2], 
    [Table field] AS [Query field 1] 
FROM [A table];

That also works.

However, one case I've found that does not work is using the alias inside a subquery. Consider the following query:

SELECT 
    (SELECT [Table field] FROM [A table] WHERE [Table field] = "1") AS [Query field 2]
FROM [A table];

Now set an alias for [Table field]:

SELECT 
    [Table field] AS [Query field 1], 
    (SELECT [Query field 1] FROM [A table] WHERE [Query field 1] = "1") AS [Query field 2]
FROM [A table];

This yields a user prompt to enter a value for the parameter [Query field 1], indicating that Access was not able to interpret the alias inside the subquery. Furthermore, the problem does not arise from the appearance of the alias in the WHERE clause. Although that clause is necessary (when it's removed from the version without the alias, we get the error, "At most one record can be returned by this subquery."), we can test whether the parameter prompt is arising in the WHERE clause by removing that clause, like so:

SELECT 
    [Table field] AS [Query field 1], 
    (SELECT [Query field 1] FROM [A table]) AS [Query field 2]
FROM [A table];

That does not yield an error, but does yield the parameter prompt, indicating that Access can't interpret the alias in the SELECT statement of the subquery.

The conclusion from all of that is that a field alias CAN be used in the same SELECT statement, but not inside a subquery of that SELECT . I think I've experienced other situations where an alias did not work in the same SELECT , but I don't remember the circumstances.

Does anyone know where there is an authoritative explanation of when a field alias can be used in Access that is not wrong like the ones cited above?

Use an alias for the sub table - something like:

SELECT 
    [A table].[Table field] AS [Query field 1], 
    (SELECT T.[Table field] FROM [A table] As T WHERE T.[Table field 1] = "1") AS [Query field 2]
FROM 
    [A table];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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