VOOZH about

URL: https://dzone.com/articles/get-last-record-in-each-mysql-group

⇱ Get Last Record in Each MySQL Group


Related

  1. DZone
  2. Data Engineering
  3. Databases
  4. Get Last Record in Each MySQL Group

Get Last Record in Each MySQL Group

In this tutorial we will look at how you can use MySQL at getting the last record in a Group By of records.

By Sep. 04, 15 · Tutorial
Likes
Comment
Save
106.7K Views

Join the DZone community and get the full member experience.

Join For Free

In this tutorial we will look at how you can use MySQL at getting the last record in a Group By of records.

For example if you have this result set of posts:

id category_id post_title
-------------------------
1 1 Title 1
2 1 Title 2
3 1 Title 3
4 2 Title 4
5 2 Title 5
6 3 Title 6

I want to be able to get the last post in each category which are Title 3, Title 5 and Title 6. To get the posts by the category you will use the MySQL Group By keyboard.

select * from posts group by category_id

But the results we get back from this query is.

id category_id post_title
-------------------------
1 1 Title 1
4 2 Title 4
6 3 Title 6

The group by will always return the first record in the group on the result set.

SELECT id, category_id, post_title
FROM posts
WHERE id IN (
 SELECT MAX(id)
 FROM posts
 GROUP BY category_id
);

This will return the posts with the highest IDs in each group.

id category_id post_title
-------------------------
3 1 Title 3
5 2 Title 5
6 3 Title 6
Database MySQL

Published at DZone with permission of Paul Underwood. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Custom Model Context Protocol (MCP) for NL2SQL: A Rigorous Evaluation Framework on Oracle Database
  • Using Arrow Flight SQL to Improve Data Transfer Performance in Apache Doris
  • Automating a Web Form With Playwright MCP and MySQL MCP
  • Master SQL Performance Optimization: Step-by-Step Techniques With Case Studies

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

Let's be friends: