HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Multiple Aliases in an SQL Query

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
sqlaliasesquerymultiple

Problem

Would it be possible to give a table in MySQL query multiple aliases?

If so how would I do this?

Solution

You can if you are using the table multiple times in different clauses and/or sub-queries like

SELECT SeniorManager = sm.displayName, Manager = m.displayName, Worker = w.displayName
FROM   people AS w
LEFT OUTER JOIN people AS  m ON  m.id = w.bossID
LEFT OUTER JOIN people AS sm ON sm.id = m.bossID


But you can not give the same use of a table more than one alias - the following for instance is invalid syntax:

SELECT a1.name, a2.name FROM people AS a1 AND a2


Also, you can not (in most DBMSs) use a table by both its real name and alias, so the following is invalid too:

SELECT people.name, a1.name FROM people AS a1


If ause of an object is given an alias you must refer to that instance by that alias even if the real name is unambiguous within the query.

Code Snippets

SELECT SeniorManager = sm.displayName, Manager = m.displayName, Worker = w.displayName
FROM   people AS w
LEFT OUTER JOIN people AS  m ON  m.id = w.bossID
LEFT OUTER JOIN people AS sm ON sm.id = m.bossID
SELECT a1.name, a2.name FROM people AS a1 AND a2
SELECT people.name, a1.name FROM people AS a1

Context

StackExchange Database Administrators Q#39323, answer score: 3

Revisions (0)

No revisions yet.