Алиасы в sql что это

SQL Псевдонимы

SQL Алиасы

Псевдонимы SQL используются для присвоения таблице или столбцу в таблице временного имени.

Псевдонимы часто используются для того, чтобы сделать имена столбцов более удобочитаемыми.

Псевдоним существует только на время выполнения запроса.

Синтаксис столбца Алиас

Синтаксис таблиц Алиас

Демо база данных

В этом уроке мы будем использовать хорошо известный пример базы данных Northwind.

Ниже приведен выбор из таблицы «Customers»:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK

И выбор из таблицы «Orders»:

OrderIDCustomerIDEmployeeIDOrderDateShipperID
103545881996-11-143
10355461996-11-151
103568661996-11-182

Примеры Алиас для столбцов

Следующий оператор SQL создает два псевдонима, один для столбца «CustomerID» и «CustomerName» для колонки:

Пример

Следующий оператор SQL создает два псевдонима, один для CustomerName колонки и для столбцов ContactName.

Примечание: Он требует двойных кавычек или квадратных скобок, если имя псевдонима содержит пробелы:

Пример

Следующий оператор SQL создает псевдоним «Address», которые объединяют четыре колонны (Address, PostalCode, City и Country):

Пример

Примечание: Чтобы получить инструкцию SQL, чтобы работать в MySQL использовать следующие:

Пример Алиас для таблиц

Следующая инструкция SQL выбирает все заказы от клиента с CustomerID=4 (вокруг рожка). Мы используем таблицы «Customers» и «Orders» и даем им псевдонимы таблиц «c» и «o» соответственно (здесь мы используем псевдонимы, чтобы сделать SQL короче):

Пример

Следующий оператор SQL такой же, как и выше, но без псевдонимов:

Пример

Алиасы могут быть полезны, когда:

Упражнения

Тесты

КАК СДЕЛАТЬ

ПОДЕЛИТЬСЯ

СЕРТИФИКАТЫ

Сообщить об ошибке

Если вы хотите сообщить об ошибке или сделать предложение, не стесняйтесь, присылайте нам электронное письмо:

Ваше предложение:

Спасибо, за вашу помощь!

Ваше сообщение было отправлено в SchoolsW3.

Топ Учебники

Топ Справочники

Топ Примеры

Веб Сертификаты

Источник

AS. Создание алиасов для таблиц и колонок в MySQL

Алиасы

Алиасы позволяют задавать более читабельные и простые имена.

Чаще всего алиасы применяются когда:

Создание алиасов для таблиц

Синтаксис создания алиаса для таблицы

Для примера возьмем БД книжного магазина Bookstore и сделаем вывод статуса и даты заказов из таблиц customers и orders для клиента с именем Jane Doherty.

mysql> SELECT customers.first_name, customers.last_name, orders.status, orders.order_date
-> FROM customers, orders
-> WHERE customers.first_name= ‘Jane’
-> AND customers.last_name= ‘Doherty’
-> AND customers.id=orders.customer_id;
+————+————+———————————+———————+
| first_name | last_name | status | order_date |
+————+————+———————————+———————+
| Jane | Doherty | Завершен | 2019-01-11 20:59:40 |
| Jane | Doherty | Готов к отправке | 2018-12-24 04:28:54 |
+————+————+———————————+———————+
2 rows in set (0.00 sec)

Теперь с помощью алиасов упростим запрос и преобразуем его к следующему виду.

mysql> SELECT c.first_name, c.last_name, o.status, o.order_date
-> FROM customers AS c, orders AS o
-> WHERE c.first_name= ‘Jane’
-> AND c.last_name= ‘Doherty’
-> AND c.id=o.customer_id;
+————+————+———————————+———————+
| first_name | last_name | status | order_date |
+————+————+———————————+———————+
| Jane | Doherty | Завершен | 2019-01-11 20:59:40 |
| Jane | Doherty | Готов к отправке | 2018-12-24 04:28:54 |
+————+————+———————————+———————+
2 rows in set (0.00 sec)

Применение алиасов при работе только с одной таблицей, будет бессмысленно.

Создание алиасов для колонок

Синтаксис создания алиаса для колонок

Выведем несколько записей из таблицы books.

mysql> SELECT id, title, author, price
-> FROM books
-> LIMIT 5;
+—-+—————————+——————-+———+
| id | title | author | price |
+—-+—————————+——————-+———+
| 1 | Дубровский | Александр Пушкин | 230.00 |
| 2 | Нос | Николай Гоголь | 255.20 |
| 3 | Мастер и Маргарита | Михаил Булгаков | 263.00 |
| 4 | Мёртвые души | Николай Гоголь | 173.00 |
| 5 | Преступление и наказание | Фёдор Достоевский | 245.00 |
+—-+—————————+——————-+———+
5 rows in set (0.00 sec)

Для простоты чтения создадим алиасы для всех колонок.

Алиасы также удобно применять для обозначения результатов функций.

Понравилась статья? Расскажите о ней друзьям!

Источник

SQL Псевдонимы

SQL псевдонимы используются для временного переименования таблицы или заголовок столбца.

Псевдонимы SQL

SQL псевдонимы используются для получения таблицы базы данных или столбец в таблице, временное имя.

В основном создаются псевдонимы, чтобы имена столбцов более удобным для чтения.

SQL Алиас Синтаксис для столбцов

SQL Синтаксис Алиас для таблиц

Демо-версия базы данных

В этом уроке мы будем использовать хорошо известную базу данных Борей.

Ниже приводится подборка из «Customers» таблицы:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitucion 2222Mexico D.F.05021Mexico
3Antonio Moreno TaqueriaAntonio MorenoMataderos 2312Mexico D.F.05023Mexico
4Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK

И выбор из «Orders» таблицы:

OrderIDCustomerIDEmployeeIDOrderDateShipperID
103545881996-11-143
10355461996-11-151
103568661996-11-182

Алиас Пример для столбцов таблицы

пример

В следующем операторе SQL мы объединим четыре столбца (Address, City, PostalCode и Country ) и создать псевдоним с именем «Address» :

пример

Алиас Пример для таблиц

пример

То же самое заявление SQL без псевдонимов:

пример

Псевдонимы могут быть полезны в следующих случаях:

Источник

SQL Aliases

SQL Aliases

Aliases SQL используются для предоставления таблицы или столбца в таблице временного имени.

Aliases часто используются, чтобы сделать имена столбцов более читаемыми.

Псевдоним существует только на протяжении запроса.

Alias Column Syntax

Alias Table Syntax

Демонстрационная база данных

В этом учебнике мы будем использовать хорошо известную базу данных Northwind Sample.

Ниже представлен выбор из таблицы «Customers»:

CustomerIDCustomerNameContactNameAddressCityPostalCodeCountry
2Ana Trujillo Emparedados y heladosAna TrujilloAvda. de la Constitución 2222México D.F.05021Mexico
3Antonio Moreno TaqueríaAntonio MorenoMataderos 2312México D.F.05023Mexico
4Around the HornThomas Hardy120 Hanover Sq.LondonWA1 1DPUK

И выбор из таблицы «Orders»:

OrderIDCustomerIDEmployeeIDOrderDateShipperID
103545881996-11-143
10355461996-11-151
103568661996-11-182

Примеры Aliases для столбцов

Следующая инструкция SQL создает два псевдонима, один для столбца идентификатора и один для столбца CustomerName:

Пример

Следующая инструкция SQL создает два псевдонима: один для столбца CustomerName и один для столбца ContactName. Примечание: Он требует двойных кавычек или квадратных скобок, если псевдоним содержит пробелы:

Пример

Следующая инструкция SQL создает псевдоним с именем «Address», объединяющий четыре столбца (адрес, PostalCode, город и страна):

Пример

Примечание: Чтобы получить инструкцию SQL выше для работы в MySQL, используйте следующее:

Пример псевдонима для таблиц

Следующая инструкция SQL выбирает все заказы от клиента с клиентом = 4 (вокруг Рога). Мы используем таблицы «Customers» и «Orders», и даем им табличные псевдонимы «c» и «o» соответственно (здесь мы используем псевдонимы, чтобы сделать SQL короче):

Пример

Следующая инструкция SQL такая же, как и выше, но без псевдонимов:

Пример

Aliases могут быть полезны, когда:

Источник

SQL Alias: A Guide to the SQL Aliases and the SQL AS Keyword

What is an alias in SQL?

It’s a name you give to a column or a table in your SQL query to make it easier to display the results or to write your query.

SQL aliases are a useful feature and are available in all major database vendors, including Oracle, SQL Server, MySQL, PostgreSQL.

There are two types of aliases in SQL: column aliases and table aliases.

SQL Column Alias

An SQL column alias is a name that you can give to a column in a query.

Алиасы в sql что это. Смотреть фото Алиасы в sql что это. Смотреть картинку Алиасы в sql что это. Картинка про Алиасы в sql что это. Фото Алиасы в sql что это

One of the most common ways to use it is in a SELECT query. The syntax for doing this is:

An example of this is this SELECT query:

The results of this query would be:

LAST_NAMEANNUAL_SALARY
SMITH40000
ANDERSON60000
JONES45000

The salary column is the column in the database, but it has been given a column name in the output.

SQL AS Keyword – Should I Use It If It’s Optional?

The SQL AS keyword is used to define a column alias. It’s also an optional keyword.

If it’s optional, should you use it?

I recommend that you do.

It makes it clear that you are using a column alias.

Consider this query that does not use the AS keyword:

This query gives an alias of annual_salary to the salary column. It will run and show you the data you need.

The database knows that annual_salary is an alias, rather than a column, because there is no comma after the previous column.

This can cause two problems:

Consider this query which is slightly different:

Notice that there is no comma after hire_date. Looking at this query, it’s not easy to see if the comma was forgotten, or if it was written to use an alias of start_date for the hire_date column.

The results will show this:

FIRST_NAMELAST_NAMEANNUAL_SALARYSTART_DATE

Notice that there is only one date column. This is the hire_date column shown as the start_date.

So, how can you avoid all of this confusion? Use the AS keyword with your column aliases.

The query above can be written as:

This makes it clear which columns are to be shown in the results and which columns have an alias.

That’s why I recommend using the AS keyword in your column aliases.

SQL Column Alias Examples

Let’s take a look at some examples of SQL column aliases.

Sample Data

This SQL can be used to set up the sample data used in this guide.

Example 1: Simple SELECT

Here’s a simple example of a SELECT statement that uses a column alias.

LAST_NAMEHIRE_DATE
SMITH1 Feb 2018
ANDERSON14 Sep 2012
JONES20 Nov 2015

The column shown as hire_date above is actually stored as hdt in the table.

Example 2: Expression

This example uses an expression and gives it a column alias.

FIRST_NAMELAST_NAMEFULL_NAME
JOHNSMITHJOHN SMITH
SALLYANDERSONSALLY ANDERSON
MARKJONESMARK JONES

The names are concatenated into a single field, which is called full_name. Without the column alias, the column name would be a lot messier.

Example 3: Function

This example uses a column alias on a function.

LAST_NAMEHIRE_DATETENURE_MONTHS
SMITH1 Feb 201815
ANDERSON14 Sep 201279
JONES20 Nov 201541

This tenure_months column shows the number of months an employee has been working for. It uses a combination of the MONTHS_BETWEEN, ROUND, and SYSDATE functions.

Example 4: Subquery

Another common use of a column alias is in a subquery. If you’re performing complicated logic but want to do further operations on it, it’s often a good idea to enclose it in a subquery.

This will allow you to:

This query uses the tenure_months, calculated from the subquery, in the outer query as both a column to display and an input into the CASE statement. Without the subquery and column alias, the query would be a lot messier.

LAST_NAMEHDTTENURE_MONTHSTENURE_STATEMENT
SMITH1 Feb 201815Less than two years
ANDERSON14 Sep 201279At least two years
JONES20 Nov 201541At least two years

SQL Table Alias

What is an SQL table alias?

It’s a short name you give to a table when you use it in an SQL query.

Table aliases can help your queries by:

The syntax of a table alias is:

The alias_name is the name given to your table to be used in the query.

The alias you use will often be a short one. Most of the aliases I use and see in other people’s code are one to three letters long. This makes it easier to type and it’s still easy to identify in a query.

Should You Use the SQL AS Keyword with Table Aliases?

The AS keyword is optional when using it with a table alias.

This means the following two queries will work:

Which should you use?

Earlier I mentioned that for column aliases, you should use AS because it makes it clear that a column alias is used.

For table aliases, I also recommend using the AS keyword. However, the impact of not using the AS keyword is not as significant. If you don’t use the AS keyword, there is no risk of tables being excluded. You’ll likely get a syntax error when you run the query, instead of a column missing in your output.

Also, on Oracle SQL, you’ll get an error if you add the AS keyword to the table alias.

So, this query will work on Oracle:

But this query will not:

Autocomplete with Table Aliases

Using a table alias also makes it easier to use the autocomplete feature of most IDEs.

In an IDE, to add a column into the SELECT statement, you’ll need to type out the full name of the column.

Using a table alias, you can enter the table alias and then a period, and then a list of available columns will appear form that table. It makes it much easier to write your query.

For example, entering your query like this will cause the list of columns to appear after you enter the “e.” into your SELECT clause.

SQL Table Alias Examples

Let’s take a look at some examples of the SQL table alias.

Example 1: Simple Query

Here’s a simple example of a table alias. We’re using the sample data from earlier in the article.

Notice that the table aliases have been used as a prefix to the column names in the SELECT clause. This is optional in many cases but is often required (if there are two tables with the same column name). It also helps to clarify which table a column exists in.

LAST_NAMESALARY
SMITH40000
ANDERSON60000
JONES45000

Example 2: Using a WHERE Clause

This example demonstrates how to use a table alias as part of the WHERE clause.

LAST_NAMESALARY
SMITH40000

Example 3: Using a Join

This example uses table aliases in a join.

Notice that both the employee_test and department_test tables have table aliases (“e” and “d”). They are used in the join condition and in the SELECT clause.

The results of this query are:

LAST_NAMESALARYDEPT_NAME
SMITH40000SALES
ANDERSON60000HR
JONES45000SALES

Example 4: Update Statement

SQL table aliases can also be used in UPDATE statements.

This query gives the table alias “e” to the employee_test table, and all of the columns within the query are prefixed with the table alias.

Here’s the table before the update:

LAST_NAMESALARYDEPT_ID
SMITH400001
ANDERSON600002
JONES450003

Here’s the table after the update:

LAST_NAMESALARYDEPT_ID
SMITH420002
ANDERSON600002
JONES450003

Conclusion

SQL allows the use of both column aliases and table aliases. This is done using the SQL AS keyword, which is an optional keyword in many SQL statements including SELECT, UPDATE, and DELETE.

Column aliases allow you to use a different and often simpler name for a column in your query.

Table aliases allow you to name your table for use in other parts of your query, such as the SELECT or WHERE clauses.

6 thoughts on “SQL Alias: A Guide to the SQL Aliases and the SQL AS Keyword”

Thanks Ben for putting all these material all in once place.
Believe me your website is like a SQL Bible for me.
It is so so helpful.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *