I have a database which have columns with
id, adsoyad, tag_id, map_id, xpos, ypos, and date.
This database receives data from each user every 15 minutes. Each user has a unique tag_id. The structure of the "date" column is in datetime format.
When I run the code below;
SELECT tag_id, xpos, ypos, adsoyad, date, MAX(date)
FROM `lt_position`
WHERE map_id="750"
GROUP BY tag_id
A column named Max(date) appears, the groupings are correct, but the Max(date) column lists the previous entry, not the last entry.
when I run this code, while listing, it lists the last registration date and the previous registration of the person.
What I want is to see the xpos and ypos data that each user submitted at the last registration time.
I tried some different code which I found in different solutions on the web and also from stackoverflow. But all of them give the same results to me.
I guessed my database has some problem. I tried to repair it a few times. I deleted and created it once. But the result is still the same.
3
Answers
Please do not include images in the question. Use text instead.
You should tell from what set you want the
max
from (max of what?). You seem to have bothdate
andmax(date)
in the query.GROUP BY
statement should include all non-aggregate columns from theSELECT
.Please execute below query to see whether the tag_id wise max date is in the top or not.
Please also execute this:
If so, that’s a typical top-1-per-group problem.
If you are running MySQL 8.0, you can solve it with window functions:
In earlier versions, where window functions are not available, one alternative uses a correlated subquery:
For performance with the second query, consider an index on
lt_position(tag_id, date)
.