E
E
Egorithm2016-05-20 17:30:41
MySQL
Egorithm, 2016-05-20 17:30:41

MySQL. Is it possible to replace UNION or how to optimize the query?

There is a database called computer_company
5fe1569404134ab5847b7d2ac3ffc9e6.pngTask:
Find the model number of the highest priced product (PC, laptop or printer).
Here is what I wrote:

(SELECT model, price FROM pc)
UNION
(SELECT model, price FROM laptop)
UNION
(SELECT model, price FROM printer)
ORDER BY price DESC LIMIT 1;

The request turned out to be rather clumsy, is there a more rational way? Is a UNION needed here?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Алексей Уколов, 2016-05-20
@EgoRusMarch

Union можно оставить, но добавить в каждый из подзапросов лимит и сортировку - зачем вам собирать полностью три таблицы, а потом выкидывать всё, кроме первой строки?
А вообще, такая структура БД - антипаттерн. Цена есть у всех продуктов, вне зависимости от типа, поэтому эта колонка должна быть в основной таблице. Не в последнюю очередь для того, чтобы избежать таких кривых выборок.

Михаил Рожков, 2016-05-20
@shogunkub

In general, there is an aggregate function MAX, but since it must be applied several times, and the item itself is needed, and not just the price, it is unlikely to be better. Namely, in this query, indeed, LIMIT with sorting in subqueries is requested, because otherwise, it turns out that one huge table is being built, and then one row is obtained from it.
There is another catch - what should be done with the same maximum price for several items? :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question