查询用于选择具有不同categoryid的不同最近记录

时间:2011-03-22 13:58:05

标签: mysql

我在mysql中有以下数据库结构。

表:故事

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

我想以某种方式选择结果,以便它只能选择4条记录,每个categoryid只有1条。

我需要显示如下结果,每个类别的最新记录。

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

是否有可能,请帮我进行此查询。

3 个答案:

答案 0 :(得分:3)

试试这个:

SELECT *
  FROM categories 
 WHERE (categoryid, date) IN 
       (
        SELECT categoryid, MAX(date)
          FROM categories
          GROUP BY categoryid
       )

答案 1 :(得分:0)

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);

答案 2 :(得分:0)

SELECT Id, Name, categoryid, date FROM story GROUP BY categoryid ORDER BY date