G
G
GreenSun2013-12-14 14:04:13
MySQL
GreenSun, 2013-12-14 14:04:13

Selecting latest data for each user from mysql

Hello dear all!
In the process of learning the truth of mysql, there is a userData table with user data for a certain time.
At present, there are 54,000 entries in the tablet, growth is planned.
Its simplified structure is: dataTime (timestamp), id (bigint user ID), data (user information in json). You cannot make changes to the structure.
time and id are unique for each row.
Task: for certain user ids, select the most recent (with the latest date) complete rows (with all columns).
We came up with several options:

(SELECT * FROM userData WHERE id=1 ORDER BY dataTime LIMIT 1) UNION
(SELECT * FROM userData WHERE id=222 ORDER BY dataTime LIMIT 1) UNION
(SELECT * FROM userData WHERE id=333 ORDER BY dataTime LIMIT 1) UNION
(SELECT * FROM userData WHERE id=444 ORDER BY dataTime LIMIT 1) UNION
(SELECT * FROM userData WHERE id=555 ORDER BY dataTime LIMIT 1)

Cool option, completed in 0.001 sec. But with an obvious minus, when requesting with 1000 IDs, logs will grow well, long requests will run and kittens will die, which we would not want to do.
SELECT * FROM userData WHERE (id, dataTime) IN (select id, max(dataTime) maxTime from userData b where id in (1, 222, 333, 444, 555) group by id)

Runs in 12 seconds, but small.
We need a variant with a short execution time, perversion is allowed.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene Mosyukov, 2013-12-14
@GreenSun

Try like this:

SELECT data.* 
FROM userData AS data
JOIN (
  SELECT id, MAX(dataTime) AS dataTime
  FROM userData
  WHERE id IN (1, 222, 333, 444, 555)
  GROUP BY id
) AS max USING (id, dataTime);

D
Dmitry Goryachev, 2013-12-14
@Gordim

See if it helps
www.sql.ru/forum/687908/faq-vyborka-pervoy-posledn...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question