SQL:只获取每个“组”的最新条目?

时间:2013-07-05 09:32:49

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

在这里,我创建了一些要测试的表:

CREATE TABLE IF NOT EXISTS `test` (
  `index` varchar(255) NOT NULL,
  `index2` varchar(255) NOT NULL,
  `date` date NOT NULL,
  `somenumber` int(10) NOT NULL,
  PRIMARY KEY (`index`,`index2`,`date`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `test` (`index`, `index2`, `date`, `somenumber`) VALUES
('kevin', 'little', '2013-06-11', 1),
('kevin', 'little', '2013-07-03', 5),
('maria', 'smith', '2013-07-01', 3),
('martin', 'luther', '2013-07-04', 13),
('martin', 'luther', '2013-07-05', 14);

现在,我想为所有人提供最新 somenumber,按somenumber DESC排序。这是我的尝试:

SELECT * FROM `test` GROUP BY `index`, `index2` ORDER BY `somenumber` DESC

问题是这个查询总是为每个组占用一个数字,但并不总是最新的。

(我知道索引名称在这里没有多大意义,但我认为这比使用随机数字索引更容易阅读)

2 个答案:

答案 0 :(得分:3)

希望这会对你有所帮助

SELECT * 
FROM  
    (SELECT * FROM `test`  ORDER BY `index`, `date` DESC) as temp
GROUP BY `index`, `index2` 
ORDER BY `somenumber` DESC

答案 1 :(得分:2)

试试这个:

SELECT t1.`INDEX`, t1.`INDEX2`, t1.`SOMENUMBER` FROM TEST t1 INNER JOIN
(SELECT `INDEX`, `INDEX2`, MAX(`DATE`) DATE FROM TEST
GROUP BY `INDEX`, `INDEX2`) t2 ON t1.INDEX = t2.INDEX AND t1.INDEX2 = t2.INDEX2 AND t1.DATE = t2.DATE