Reputation: 27195
I have following db structure in mysql.
Table: Story
Id Name categoryid date
1 Pa 4 2011-03-22 09:56:15
2 Pb 1 2011-03-23 09:56:16
3 Pc 2 2011-03-24 09:56:17
4 Pd 3 2011-03-25 09:56:18
5 Pe 1 2011-03-26 09:56:19
6 Pf 2 2011-03-27 09:56:20
7 Pg 3 2011-03-28 09:56:22
8 Ph 1 2011-03-29 09:56:23
I want to select results in a way so that it should select only 4 records, 1 for each categoryid.
I need to show result as below, latest record from each category.
Id Name categoryid date
8 Ph 1 2011-03-29 09:56:23
6 Pf 2 2011-03-27 09:56:20
7 Pg 3 2011-03-28 09:56:22
1 Pa 4 2011-03-22 09:56:15
Is it possible, please help me to make this query.
Upvotes: 0
Views: 127
Reputation: 6943
SELECT Id, Name, categoryid, date FROM story GROUP BY categoryid ORDER BY date
Upvotes: 0
Reputation: 56397
select t1.* from categories as t1
inner join (
select categoryid,max(date) as date
from categories
group by categoryid) as t2
on t1.categoryid = t2.categoryid and t1.date = t2.date
alter table categories add index i (categoryid,date);
Upvotes: 0
Reputation: 82933
Try this:
SELECT *
FROM categories
WHERE (categoryid, date) IN
(
SELECT categoryid, MAX(date)
FROM categories
GROUP BY categoryid
)
Upvotes: 3