P
P
Pavel2015-10-27 21:04:59
MySQL
Pavel, 2015-10-27 21:04:59

Which query is the best?

At one of the interviews, they gave a test task:
There is a table like
+----+--------+------------+-------+
| id | type | date | value |
+----+--------+----+-------+
| 1 | photo | 2015-02-02 | 1240 |
+----+--------+----+-------+
| 2 | image | 2015-02-02 | 5609 |
+----+--------+----+-------+
...
+----+----- ---+-----------+-------+
| 50 | photo | 2015-02-01 | 1190 |
+----+--------+----+-------+
| 51 | review | 2015-02-02 | 3600 |
+----+--------+----+-------+
The table contains data with the values ​​of some entities on different dates. The entity set is limited. The data in the table is updated every day, but it may happen that in some of the days there is no data for some entities. It is necessary to write a query that will get the most "fresh" values ​​for each entity. If for the current day there is no value for any of the entities, then you must select the previous value, and so on. The result should be a table like:
+--------+------+
| photo | 1240 |
+--------+------+
| image | 5609 |
+--------+------+
| review | 3600 |
+--------+------+
Suggested this query:
SELECT d1.type, d1.value
FROM data d1
JOIN (SELECT type, MAX(date) date
FROM data
GROUP BY type) d2
ON d1.type = d2.type AND d1.date = d2.date
They said that this is not the optimal solution.
They are right? Is there any better solution?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Aleksey Ratnikov, 2015-10-27
@ambrous

select
  type, value
from data as d1
where date = (select max(date) from data as d2 where d2.type = d1.type);

Here is a better query.

E
evnuh, 2015-10-27
@evnuh

joke from me: the most optimal query is always the one that starts with EXPLAIN.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question