D
D
dflbrhekbn2016-07-11 11:56:56
MySQL
dflbrhekbn, 2016-07-11 11:56:56

How to correctly assign aliases to tables and columns in mysql?

I do tasks on the site www.sql-ex.ru and in some places I look through the answers to some tasks where I can’t do it myself. And now I repeatedly meet requests where t1, t2, t3, etc. are used instead of the table name. For example:
SELECT model
FROM (
SELECT model, price
FROM pc
UNION
SELECT model, price
FROM Laptop
UNION
SELECT model, price
FROM Printer
) t1
WHERE price = (
SELECT MAX(price)
FROM (
SELECT price
FROM pc
UNION
SELECT price
FROM Laptop
UNION
SELECT price
FROM Printer
) t2
);
I found that it is called an alias and read about them and AS. And now I can’t understand why the example above works, but mine:
SELECT model
FROM t1
WHERE model = 1401
After all, t1 is used instead of the table name here and there. Besides, I don't see AS.
Explain to me fool!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Entelis, 2016-07-11
@DmitriyEntelis

dflbrhekbn : AS keyword can be skipped
equivalently

select .. FROM (
SELECT model, price
FROM pc
UNION
SELECT model, price
FROM Laptop
UNION
SELECT model, price
FROM Printer
) t1
means that for this query a virtual table is created in which the result of the execution "SELECT model, price FROM pc UNION SELECT model, price FROM Laptop UNION SELECT model, price
FROM Printer" is placed and the alias t1 is assigned to it in this query.
By the way, virtual tables work wildly slowly.

M
Maxim Fedorov, 2016-07-11
@qonand

if you carefully look at the example, you will see that there is a select from the subquery, which is assigned an alias. What is aliased in your code? nothing... it should be

SELECT model
FROM table_name AS t1
WHERE model = 1401

those. you must assign an alias to either a specific table, or a specific field, or a specific selection

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question