Answer the question
In order to leave comments, you need to log in
MySQL. Is it possible to replace UNION or how to optimize the query?
There is a database called computer_company
Task:
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;
Answer the question
In order to leave comments, you need to log in
Union можно оставить, но добавить в каждый из подзапросов лимит и сортировку - зачем вам собирать полностью три таблицы, а потом выкидывать всё, кроме первой строки?
А вообще, такая структура БД - антипаттерн. Цена есть у всех продуктов, вне зависимости от типа, поэтому эта колонка должна быть в основной таблице. Не в последнюю очередь для того, чтобы избежать таких кривых выборок.
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 questionAsk a Question
731 491 924 answers to any question