- For individual users
- Instant access to solutions
- Ask your tech questions
- Start your 30-day Free Trial
Main Topics
Browse All TopicsI want to list all the post categories, while also showing the most recent post from that category. Can't figure this one out. Here are example tables:
CREATE TABLE `categories` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
CREATE TABLE `posts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(50) NOT NULL,
`body` text NOT NULL,
`date_created` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
CREATE TABLE `posts_to_categories` (
`post_id` int(10) unsigned NOT NULL,
`category_id` int(10) unsigned NOT NULL
) ENGINE=InnoDB;
And some sample data:
INSERT INTO `categories` (`id`, `name`) VALUES
(1, 'Vacation'),
(2, 'Family');
INSERT INTO `posts` (`id`, `title`, `body`, `date_created`) VALUES
(1, 'Paris', 'Here are some pictures', '2009-04-11 15:45:39'),
(2, 'Spain', 'What a great trip!', '2009-04-12 15:45:52'),
(3, 'The kids', 'The latest pictures', '2009-04-11 15:46:26'),
(4, 'Mom & Dad', 'Enjoying mom''s birthday', '2009-04-12 15:46:44');
INSERT INTO `posts_to_categories` (`post_id`, `category_id`) VALUES
(1, 1),
(2, 1),
(3, 2),
(4, 2);
The query would produce results like this:
1) Vacation
- What a great trip!
2) Family
- Enjoying mom's birthday
That is, each category, along with the category's most recent post.
This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
Business Accounts
Answer for Membership
by: racekPosted on 2009-04-13 at 13:15:24ID: 24132539
SELECT name, title
FROM categories c, posts p,
(SELECT category_id, MAX(post_id) pst_id
from posts_to_categories group by 1) x
WHERE c.id = x.category_id and p.id = x.pst_id;