MySQL需要有关Query的建议

时间:2014-11-29 09:57:48

标签: mysql sql select group-by greatest-n-per-group

我想从每种新闻类型中获取最新的3条新闻。

CREATE TABLE IF NOT EXISTS `news` (
  `news_id` int(8) NOT NULL AUTO_INCREMENT,
  `news_heading` tinytext NOT NULL,
  `news_description` text NOT NULL,
  `news_date` date DEFAULT NOT NULL,
  `news_type` tinyint(1) NOT NULL COMMENT '0- PEP|1 - MEDIA|2 - CONSULTING',
  `created_date` datetime NOT NULL,
  `modified_date` datetime NULL,
  `display` tinyint(1) NOT NULL COMMENT '0- ON | 1 -OFF',
  PRIMARY KEY (`news_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

以下查询只会向我提供所有类型的最新消息。建议我如何从每种类型中获得前三名

SELECT * FROM (
SELECT * FROM  `news` 
ORDER BY  `created_date` DESC
) AS TBL
GROUP BY  `news_type`

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT news_id, news_heading, news_description, news_date, 
       news_type, created_date, modified_date, display
FROM (SELECT news_id, news_heading, news_description, news_date, 
             news_type, created_date, modified_date, display, 
             IF(@news_type = @news_type:=news_type, @id:=@id+1, @id:=1) AS id 
      FROM news, (SELECT @id:=1, @news_type:=0) A 
      ORDER BY news_type, created_date DESC
     ) AS A 
WHERE id <= 3;