I’m running a MySQL query to get the highest ID of each row grouped by each field. I do this with:
SELECT period,max(id) AS maxid
FROM f
WHERE type = '1'
GROUP BY period
This produces:
+--------+-------+
| period | maxid |
+--------+-------+
| 1 | 21878 |
| 2 | 21879 |
| 3 | 20188 |
| 4 | 21873 |
| 5 | 21872 |
| 6 | 21874 |
| 7 | 21875 |
| 8 | 21876 |
| 9 | 21877 |
+--------+-------+
This is the result I am expecting.
However, I now want to run a query which returns the maximum id but one for each period. I figured the best way to do this would be to use the offset paramater on LIMIT. To test that this will work, I ran:
SELECT period,(SELECT id FROM freight_data ORDER BY id DESC LIMIT 1) AS maxid
FROM f
WHERE type = '1'
GROUP BY period
This produces:
+--------+-------+
| period | maxid |
+--------+-------+
| 1 | 21903 |
| 2 | 21903 |
| 3 | 21903 |
| 4 | 21903 |
| 5 | 21903 |
| 6 | 21903 |
| 7 | 21903 |
| 8 | 21903 |
| 9 | 21903 |
+--------+-------+
I can see why this is happening, as my subquery isn’t taking any of the conditions in to account when getting the ID, so it’s just returning the highest ID in the table.
Thus, my questions are:
- How does MAX work? and
- Is there a way I can product a similar result as max(id) but offset by one result?
Any help will be greatly appreciated!
Thanks
You could do this, which is only slightly horrible:
EDIT:
If every id belongs to only one period, I think you can use this:
However, you will not get results for periods with only one row. Of course, you could code around that.