Answer the question
In order to leave comments, you need to log in
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)
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)
Answer the question
In order to leave comments, you need to log in
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);
See if it helps
www.sql.ru/forum/687908/faq-vyborka-pervoy-posledn...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question