mysql>
SELECT artist_id id FROM artist WHERE artist_name = "New Order";+----+
| id |
+----+
| 1 |
+----+
1 row inset sec)
We
recommend using the AS
keyword, since it helps to clearly distinguish an aliased column, especially where you’re selecting multiple columns from a list of columns separated by commas.
Alias names have few restrictions. They can beat most 255 characters in length and can contain any character. If you plan to use characters
that might confuse the MySQLparser—such as periods, commas, or semicolons—make sure you enclose the alias name in backticks. We recommend using lowercase alphanumeric strings for alias names and using a consistent character choice—such as an underscore—to separate words. Aliases are case-insensitive on all platforms.
Table AliasesTable aliases are useful for the
same reasons as column aliases, but they are also sometimes the only way to express a query. This section shows you how to use table aliases,
and Nested
Queries later in this chapter, shows you other sample queries where table aliases are essential.
Here’s a basic table-alias example that shows you how to save some typing:
mysql>
SELECT ar.artist_id, al.album_name, ar.artist_name FROM -> album AS al INNER JOIN artist AS ar -> USING (artist_id) WHERE al.album_name = "Brotherhood";+-----------+-------------+-------------+
| artist_id | album_name | artist_name |
+-----------+-------------+-------------+
| 1 | Brotherhood | New Order |
+-----------+-------------+-------------+
1 row inset sec)
You can see that the album and artist tables are aliased as al and ar
, respectively, using the
AS
keyword. This allows you to express
column names more compactly, such as ar.artist_id
. Notice also that you can use table aliases in the
WHERE
clause;
unlike column aliases, there are no restrictions on where table aliases can be used in queries.
From our example, you can see that we’re referring to the table aliases before they have been defined.
As
with column aliases, the
AS
keyword is optional. This means that:
album AS al INNER JOIN artist AS ar is the same as:
Share with your friends: